judgy 0.0.1 → 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/README.md +195 -7
- package/dist/answer/index.d.ts +9 -0
- package/dist/answer/index.js +15 -0
- package/dist/answer/types.d.ts +37 -0
- package/dist/answer/types.js +0 -0
- package/dist/client/index.d.ts +3 -0
- package/dist/client/index.js +16 -0
- package/dist/client/judgy.d.ts +11 -0
- package/dist/client/judgy.js +28 -0
- package/dist/client/types.d.ts +24 -0
- package/dist/client/types.js +0 -0
- package/dist/context/image.d.ts +8 -0
- package/dist/context/image.js +36 -0
- package/dist/context/index.d.ts +3 -0
- package/dist/context/index.js +21 -0
- package/dist/context/types.d.ts +27 -0
- package/dist/context/types.js +0 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/providers/clef.d.ts +21 -0
- package/dist/providers/clef.js +47 -0
- package/dist/providers/google.d.ts +13 -0
- package/dist/providers/google.js +41 -0
- package/dist/providers/jev/answers.d.ts +4 -0
- package/dist/providers/jev/answers.js +45 -0
- package/dist/providers/jev/index.d.ts +16 -0
- package/dist/providers/jev/index.js +43 -0
- package/dist/providers/jev/questions.d.ts +14 -0
- package/dist/providers/jev/questions.js +35 -0
- package/dist/providers/jev/types.d.ts +6 -0
- package/dist/providers/jev/types.js +0 -0
- package/dist/providers/luna/answers.d.ts +7 -0
- package/dist/providers/luna/answers.js +63 -0
- package/dist/providers/luna/index.d.ts +12 -0
- package/dist/providers/luna/index.js +18 -0
- package/dist/providers/luna/questions.d.ts +10 -0
- package/dist/providers/luna/questions.js +43 -0
- package/dist/providers/provider.d.ts +27 -0
- package/dist/providers/provider.js +61 -0
- package/dist/providers/read.d.ts +17 -0
- package/dist/providers/read.js +65 -0
- package/dist/providers/types.d.ts +8 -0
- package/dist/providers/types.js +0 -0
- package/dist/question/index.d.ts +3 -0
- package/dist/question/index.js +44 -0
- package/dist/question/types.d.ts +42 -0
- package/dist/question/types.js +0 -0
- package/dist/question/validate.d.ts +7 -0
- package/dist/question/validate.js +46 -0
- package/dist/types.d.ts +5 -0
- package/dist/types.js +0 -0
- package/package.json +34 -6
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Answer } from '../../answer/types.ts';
|
|
2
|
+
import type { AnyQuestion } from '../../question/types.ts';
|
|
3
|
+
/** Reads a System One `answers` map, keyed as `systemOneQuestions` sent it. */
|
|
4
|
+
export declare const systemOneAnswers: (answers: unknown, questions: readonly AnyQuestion[]) => Record<string, Answer>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { settle } from "../../answer/index.js";
|
|
2
|
+
import { JudgyError } from "../../errors.js";
|
|
3
|
+
import { distribution, object, option, probability, scoreValue } from "../read.js";
|
|
4
|
+
import { wireKey, wireTypes } from "./questions.js";
|
|
5
|
+
const read = (question, raw) => {
|
|
6
|
+
switch (question.kind) {
|
|
7
|
+
case 'bool': {
|
|
8
|
+
const yes = probability(raw.noul, 'noul');
|
|
9
|
+
return { ok: true, value: yes >= 0.5, probability: yes, raw };
|
|
10
|
+
}
|
|
11
|
+
case 'choice': {
|
|
12
|
+
const given = object(raw.probabilities, 'probabilities');
|
|
13
|
+
const probabilities = Object.fromEntries(question.options.map((name) => [name, probability(given[name], name)]));
|
|
14
|
+
distribution(Object.values(probabilities));
|
|
15
|
+
return {
|
|
16
|
+
ok: true,
|
|
17
|
+
value: option(raw.choice, question.options),
|
|
18
|
+
confidence: probability(raw.confidence, 'confidence'),
|
|
19
|
+
probabilities,
|
|
20
|
+
raw
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
case 'score': {
|
|
24
|
+
const given = object(raw.probabilities, 'probabilities');
|
|
25
|
+
return {
|
|
26
|
+
ok: true,
|
|
27
|
+
value: scoreValue(raw.score, question.levels.length),
|
|
28
|
+
confidence: probability(raw.confidence, 'confidence'),
|
|
29
|
+
probabilities: distribution(question.levels.map((_, level) => probability(given[String(level)], `level ${level}`))),
|
|
30
|
+
raw
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
/** Reads a System One `answers` map, keyed as `systemOneQuestions` sent it. */
|
|
36
|
+
export const systemOneAnswers = (answers, questions) => {
|
|
37
|
+
const byKey = object(answers, 'answers');
|
|
38
|
+
return settle(questions, (question, index) => {
|
|
39
|
+
const raw = object(byKey[wireKey(index)], `the answer to "${question.id}"`);
|
|
40
|
+
const type = wireTypes[question.kind];
|
|
41
|
+
if (raw.type !== type)
|
|
42
|
+
throw new JudgyError(`Expected a ${type} answer to "${question.id}".`);
|
|
43
|
+
return read(question, raw);
|
|
44
|
+
});
|
|
45
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { Provider } from '../provider.ts';
|
|
2
|
+
import type { Answer } from '../../answer/types.ts';
|
|
3
|
+
import type { Context } from '../../context/types.ts';
|
|
4
|
+
import type { AnyQuestion } from '../../question/types.ts';
|
|
5
|
+
import type { ProviderRequest } from '../types.ts';
|
|
6
|
+
/**
|
|
7
|
+
* Jev, by TypeSafe, on the System One API: https://docs.typesafe.ai/api/system-one
|
|
8
|
+
*
|
|
9
|
+
* Images travel in `assets` under a fresh UUID each, and the state names them by that UUID
|
|
10
|
+
* where they appear. Requests with images must opt in with the `TypeSafe-Danger-Zone-Images` header.
|
|
11
|
+
*/
|
|
12
|
+
export declare class JevProvider extends Provider {
|
|
13
|
+
readonly name = "jev";
|
|
14
|
+
protected buildRequest(context: Context, questions: readonly AnyQuestion[]): ProviderRequest;
|
|
15
|
+
protected parseAnswers(body: unknown, questions: readonly AnyQuestion[]): Record<string, Answer>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { fitImages } from "../../context/image.js";
|
|
2
|
+
import { object } from "../read.js";
|
|
3
|
+
import { Provider } from "../provider.js";
|
|
4
|
+
import { systemOneAnswers } from "./answers.js";
|
|
5
|
+
import { systemOneQuestions } from "./questions.js";
|
|
6
|
+
/**
|
|
7
|
+
* Jev, by TypeSafe, on the System One API: https://docs.typesafe.ai/api/system-one
|
|
8
|
+
*
|
|
9
|
+
* Images travel in `assets` under a fresh UUID each, and the state names them by that UUID
|
|
10
|
+
* where they appear. Requests with images must opt in with the `TypeSafe-Danger-Zone-Images` header.
|
|
11
|
+
*/
|
|
12
|
+
export class JevProvider extends Provider {
|
|
13
|
+
name = 'jev';
|
|
14
|
+
buildRequest(context, questions) {
|
|
15
|
+
const assets = {};
|
|
16
|
+
// TypeSafe rejects images over 16 MiB, and with them the whole request.
|
|
17
|
+
const { parts } = fitImages(context, { bytes: 16 * 1024 * 1024 }, this.name);
|
|
18
|
+
const state = parts.map((part) => {
|
|
19
|
+
if (part.type === 'text')
|
|
20
|
+
return part.text;
|
|
21
|
+
const reference = crypto.randomUUID();
|
|
22
|
+
assets[reference] = { type: 'image', format: part.format, data_base64: part.base64 };
|
|
23
|
+
return reference;
|
|
24
|
+
});
|
|
25
|
+
const hasImages = Object.keys(assets).length > 0;
|
|
26
|
+
return {
|
|
27
|
+
url: 'https://api.typesafe.ai/v1/systemone',
|
|
28
|
+
headers: {
|
|
29
|
+
Authorization: `Bearer ${this.key}`,
|
|
30
|
+
...(hasImages && { 'TypeSafe-Danger-Zone-Images': 'true' })
|
|
31
|
+
},
|
|
32
|
+
body: {
|
|
33
|
+
model: this.model,
|
|
34
|
+
state: state.length === 1 ? state[0] : state,
|
|
35
|
+
questions: systemOneQuestions(questions, 'typesafe'),
|
|
36
|
+
...(hasImages && { assets })
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
parseAnswers(body, questions) {
|
|
41
|
+
return systemOneAnswers(object(body, 'the response').answers, questions);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AnyQuestion } from '../../question/types.ts';
|
|
2
|
+
import type { SystemOneStyle } from './types.ts';
|
|
3
|
+
export declare const wireTypes: {
|
|
4
|
+
readonly bool: "noul";
|
|
5
|
+
readonly choice: "choice";
|
|
6
|
+
readonly score: "score";
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The key a question travels under. Keys never reach the model, so short index keys
|
|
10
|
+
* sidestep each provider's own key rules and any id the caller picks still works.
|
|
11
|
+
*/
|
|
12
|
+
export declare const wireKey: (index: number) => string;
|
|
13
|
+
/** The `questions` map of a System One request. */
|
|
14
|
+
export declare const systemOneQuestions: (questions: readonly AnyQuestion[], style: SystemOneStyle) => Record<string, unknown>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export const wireTypes = { bool: 'noul', choice: 'choice', score: 'score' };
|
|
2
|
+
/**
|
|
3
|
+
* The key a question travels under. Keys never reach the model, so short index keys
|
|
4
|
+
* sidestep each provider's own key rules and any id the caller picks still works.
|
|
5
|
+
*/
|
|
6
|
+
export const wireKey = (index) => `q${index}`;
|
|
7
|
+
const criteria = (question, style) => {
|
|
8
|
+
switch (question.kind) {
|
|
9
|
+
case 'bool':
|
|
10
|
+
if (!question.criteria)
|
|
11
|
+
return undefined;
|
|
12
|
+
if (style === 'typesafe')
|
|
13
|
+
return question.criteria;
|
|
14
|
+
return {
|
|
15
|
+
true_description: question.criteria.true,
|
|
16
|
+
false_description: question.criteria.false
|
|
17
|
+
};
|
|
18
|
+
case 'choice':
|
|
19
|
+
return Object.fromEntries(question.options.map((option) => [
|
|
20
|
+
option,
|
|
21
|
+
question.criteria?.[option] ?? (style === 'google' ? '' : null)
|
|
22
|
+
]));
|
|
23
|
+
case 'score':
|
|
24
|
+
return question.levels;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/** The `questions` map of a System One request. */
|
|
28
|
+
export const systemOneQuestions = (questions, style) => Object.fromEntries(questions.map((question, index) => [
|
|
29
|
+
wireKey(index),
|
|
30
|
+
{
|
|
31
|
+
type: wireTypes[question.kind],
|
|
32
|
+
instructions: question.prompt,
|
|
33
|
+
criteria: criteria(question, style)
|
|
34
|
+
}
|
|
35
|
+
]));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a provider spells the System One question fields that Jev defines and Clef and Gemini reuse.
|
|
3
|
+
* `typesafe` sends bool criteria as `{ true, false }` and a missing option description as `null`.
|
|
4
|
+
* `google` sends `{ true_description, false_description }` and `""`.
|
|
5
|
+
*/
|
|
6
|
+
export type SystemOneStyle = 'typesafe' | 'google';
|
|
File without changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Answer } from '../../answer/types.ts';
|
|
2
|
+
import type { AnyQuestion } from '../../question/types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Answers are matched by the name they echo, so one missing answer can't shift the others.
|
|
5
|
+
* A refusal fails only its own question.
|
|
6
|
+
*/
|
|
7
|
+
export declare const lunaAnswers: (body: unknown, questions: readonly AnyQuestion[]) => Record<string, Answer>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { settle } from "../../answer/index.js";
|
|
2
|
+
import { JudgyError } from "../../errors.js";
|
|
3
|
+
import { distribution, isObject, list, object, option, probability, scoreValue } from "../read.js";
|
|
4
|
+
/** The one item matching `match`, so a missing or repeated item fails instead of guessing. */
|
|
5
|
+
const only = (items, match, label) => {
|
|
6
|
+
const found = items.filter(match);
|
|
7
|
+
if (found.length !== 1)
|
|
8
|
+
throw new JudgyError(`Expected one ${label}, got ${found.length}.`);
|
|
9
|
+
return object(found[0], label);
|
|
10
|
+
};
|
|
11
|
+
/** The probability OpenAI gave one value, from a `[{ value, probability }]` list. */
|
|
12
|
+
const probabilityOf = (raw, value) => {
|
|
13
|
+
const entries = list(raw.probabilities, 'probabilities').filter(isObject);
|
|
14
|
+
const label = `probability for ${JSON.stringify(value)}`;
|
|
15
|
+
return probability(only(entries, (entry) => entry.value === value, label).probability, label);
|
|
16
|
+
};
|
|
17
|
+
const expectType = (raw, type) => {
|
|
18
|
+
if (raw.type !== type)
|
|
19
|
+
throw new JudgyError(`Expected a ${type} answer.`);
|
|
20
|
+
};
|
|
21
|
+
const read = (question, raw) => {
|
|
22
|
+
switch (question.kind) {
|
|
23
|
+
case 'bool': {
|
|
24
|
+
expectType(raw, question.criteria ? 'choice' : 'predicate');
|
|
25
|
+
const yes = question.criteria
|
|
26
|
+
? probabilityOf(raw, true)
|
|
27
|
+
: probability(raw.probability, 'probability');
|
|
28
|
+
if (question.criteria)
|
|
29
|
+
distribution([yes, probabilityOf(raw, false)]);
|
|
30
|
+
return { ok: true, value: yes >= 0.5, probability: yes, raw };
|
|
31
|
+
}
|
|
32
|
+
case 'choice': {
|
|
33
|
+
expectType(raw, 'choice');
|
|
34
|
+
const probabilities = Object.fromEntries(question.options.map((name) => [name, probabilityOf(raw, name)]));
|
|
35
|
+
distribution(Object.values(probabilities));
|
|
36
|
+
const value = option(raw.choice, question.options);
|
|
37
|
+
const confidence = probability(raw.confidence, 'confidence');
|
|
38
|
+
return { ok: true, value, confidence, probabilities, raw };
|
|
39
|
+
}
|
|
40
|
+
case 'score':
|
|
41
|
+
expectType(raw, 'score');
|
|
42
|
+
return {
|
|
43
|
+
ok: true,
|
|
44
|
+
value: scoreValue(raw.score, question.levels.length),
|
|
45
|
+
confidence: probability(raw.confidence, 'confidence'),
|
|
46
|
+
probabilities: distribution(question.levels.map((_, level) => probabilityOf(raw, level))),
|
|
47
|
+
raw
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Answers are matched by the name they echo, so one missing answer can't shift the others.
|
|
53
|
+
* A refusal fails only its own question.
|
|
54
|
+
*/
|
|
55
|
+
export const lunaAnswers = (body, questions) => {
|
|
56
|
+
const answers = list(object(body, 'the response').answers, 'answers').filter(isObject);
|
|
57
|
+
return settle(questions, (question) => {
|
|
58
|
+
const raw = only(answers, (answer) => answer.name === question.id, `answer to "${question.id}"`);
|
|
59
|
+
if (raw.type === 'refusal')
|
|
60
|
+
throw new JudgyError(`luna declined to answer "${question.id}".`);
|
|
61
|
+
return read(question, raw);
|
|
62
|
+
});
|
|
63
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Provider } from '../provider.ts';
|
|
2
|
+
import type { Answer } from '../../answer/types.ts';
|
|
3
|
+
import type { Context } from '../../context/types.ts';
|
|
4
|
+
import type { AnyQuestion } from '../../question/types.ts';
|
|
5
|
+
import type { ProviderRequest } from '../types.ts';
|
|
6
|
+
/** GPT Luna decisions, on the OpenAI Decisions API: https://developers.openai.com/api/docs/guides/decisions */
|
|
7
|
+
export declare class LunaProvider extends Provider {
|
|
8
|
+
readonly name = "luna";
|
|
9
|
+
readonly maxQuestions = 400;
|
|
10
|
+
protected buildRequest(context: Context, questions: readonly AnyQuestion[]): ProviderRequest;
|
|
11
|
+
protected parseAnswers(body: unknown, questions: readonly AnyQuestion[]): Record<string, Answer>;
|
|
12
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Provider } from "../provider.js";
|
|
2
|
+
import { lunaAnswers } from "./answers.js";
|
|
3
|
+
import { lunaInput, lunaQuestion } from "./questions.js";
|
|
4
|
+
/** GPT Luna decisions, on the OpenAI Decisions API: https://developers.openai.com/api/docs/guides/decisions */
|
|
5
|
+
export class LunaProvider extends Provider {
|
|
6
|
+
name = 'luna';
|
|
7
|
+
maxQuestions = 400;
|
|
8
|
+
buildRequest(context, questions) {
|
|
9
|
+
return {
|
|
10
|
+
url: 'https://api.openai.com/v1/decisions',
|
|
11
|
+
headers: { Authorization: `Bearer ${this.key}` },
|
|
12
|
+
body: { model: this.model, input: lunaInput(context), questions: questions.map(lunaQuestion) }
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
parseAnswers(body, questions) {
|
|
16
|
+
return lunaAnswers(body, questions);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Context } from '../../context/types.ts';
|
|
2
|
+
import type { AnyQuestion } from '../../question/types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* One question in OpenAI's format. A bool with criteria becomes a choice between `true` and
|
|
5
|
+
* `false`, because predicates take no descriptions. Score levels have no separate label in
|
|
6
|
+
* judgy, so each level's text is its label.
|
|
7
|
+
*/
|
|
8
|
+
export declare const lunaQuestion: (question: AnyQuestion) => unknown;
|
|
9
|
+
/** A lone text goes as a string; anything else as one user message with ordered parts. */
|
|
10
|
+
export declare const lunaInput: ({ parts }: Context) => unknown;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { dataUrl } from "../../context/image.js";
|
|
2
|
+
/**
|
|
3
|
+
* One question in OpenAI's format. A bool with criteria becomes a choice between `true` and
|
|
4
|
+
* `false`, because predicates take no descriptions. Score levels have no separate label in
|
|
5
|
+
* judgy, so each level's text is its label.
|
|
6
|
+
*/
|
|
7
|
+
export const lunaQuestion = (question) => {
|
|
8
|
+
const base = { name: question.id, instructions: question.prompt };
|
|
9
|
+
switch (question.kind) {
|
|
10
|
+
case 'bool':
|
|
11
|
+
if (!question.criteria)
|
|
12
|
+
return { type: 'predicate', ...base };
|
|
13
|
+
return {
|
|
14
|
+
type: 'choice',
|
|
15
|
+
...base,
|
|
16
|
+
choices: [
|
|
17
|
+
{ value: true, description: question.criteria.true },
|
|
18
|
+
{ value: false, description: question.criteria.false }
|
|
19
|
+
]
|
|
20
|
+
};
|
|
21
|
+
case 'choice':
|
|
22
|
+
return {
|
|
23
|
+
type: 'choice',
|
|
24
|
+
...base,
|
|
25
|
+
choices: question.options.map((value) => ({
|
|
26
|
+
value,
|
|
27
|
+
description: question.criteria?.[value]
|
|
28
|
+
}))
|
|
29
|
+
};
|
|
30
|
+
case 'score':
|
|
31
|
+
return { type: 'score', ...base, levels: question.levels.map((label) => ({ label })) };
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
/** A lone text goes as a string; anything else as one user message with ordered parts. */
|
|
35
|
+
export const lunaInput = ({ parts }) => {
|
|
36
|
+
const [only] = parts;
|
|
37
|
+
if (parts.length === 1 && only?.type === 'text')
|
|
38
|
+
return only.text;
|
|
39
|
+
const content = parts.map((part) => part.type === 'text'
|
|
40
|
+
? { type: 'input_text', text: part.text }
|
|
41
|
+
: { type: 'input_image', image_url: dataUrl(part) });
|
|
42
|
+
return [{ role: 'user', content }];
|
|
43
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Answer } from '../answer/types.ts';
|
|
2
|
+
import type { Fetch } from '../client/types.ts';
|
|
3
|
+
import type { Context } from '../context/types.ts';
|
|
4
|
+
import type { AnyQuestion } from '../question/types.ts';
|
|
5
|
+
import type { ProviderRequest } from './types.ts';
|
|
6
|
+
/**
|
|
7
|
+
* The contract every provider implements.
|
|
8
|
+
*
|
|
9
|
+
* `run` is shared: it sends the request and turns failures into failed answers.
|
|
10
|
+
* A provider only says how to build its request and how to read its response.
|
|
11
|
+
*/
|
|
12
|
+
export declare abstract class Provider {
|
|
13
|
+
/** Short provider name, used in error messages. */
|
|
14
|
+
abstract readonly name: string;
|
|
15
|
+
/** The most questions one request may carry. `run` throws past it, before sending. */
|
|
16
|
+
readonly maxQuestions: number;
|
|
17
|
+
protected readonly key: string;
|
|
18
|
+
protected readonly model: string;
|
|
19
|
+
protected readonly fetch: Fetch;
|
|
20
|
+
constructor(key: string, model: string, fetch: Fetch);
|
|
21
|
+
/** Sends all questions in one request and resolves to answers keyed by question id. */
|
|
22
|
+
run(context: Context, questions: readonly AnyQuestion[]): Promise<Record<string, Answer>>;
|
|
23
|
+
/** Maps the context and questions to this provider's HTTP request. */
|
|
24
|
+
protected abstract buildRequest(context: Context, questions: readonly AnyQuestion[]): ProviderRequest;
|
|
25
|
+
/** Maps this provider's parsed JSON response to answers keyed by question id. */
|
|
26
|
+
protected abstract parseAnswers(body: unknown, questions: readonly AnyQuestion[]): Record<string, Answer>;
|
|
27
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { failAll, toJudgyError } from "../answer/index.js";
|
|
2
|
+
import { JudgyError } from "../errors.js";
|
|
3
|
+
import { errorMessage } from "./read.js";
|
|
4
|
+
/** Parses the body as JSON. A failed response may carry plain text, which is kept as is. */
|
|
5
|
+
const readBody = async (response, name) => {
|
|
6
|
+
const text = await response.text();
|
|
7
|
+
try {
|
|
8
|
+
return JSON.parse(text);
|
|
9
|
+
}
|
|
10
|
+
catch (cause) {
|
|
11
|
+
if (!response.ok)
|
|
12
|
+
return text;
|
|
13
|
+
throw new JudgyError(`${name} returned a response that is not JSON.`, { cause });
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The contract every provider implements.
|
|
18
|
+
*
|
|
19
|
+
* `run` is shared: it sends the request and turns failures into failed answers.
|
|
20
|
+
* A provider only says how to build its request and how to read its response.
|
|
21
|
+
*/
|
|
22
|
+
export class Provider {
|
|
23
|
+
/** The most questions one request may carry. `run` throws past it, before sending. */
|
|
24
|
+
maxQuestions = Infinity;
|
|
25
|
+
key;
|
|
26
|
+
model;
|
|
27
|
+
fetch;
|
|
28
|
+
constructor(key, model, fetch) {
|
|
29
|
+
this.key = key;
|
|
30
|
+
this.model = model;
|
|
31
|
+
this.fetch = fetch;
|
|
32
|
+
}
|
|
33
|
+
/** Sends all questions in one request and resolves to answers keyed by question id. */
|
|
34
|
+
async run(context, questions) {
|
|
35
|
+
const { fetch, name } = this;
|
|
36
|
+
let body;
|
|
37
|
+
try {
|
|
38
|
+
const request = this.buildRequest(context, questions);
|
|
39
|
+
const response = await fetch(request.url, {
|
|
40
|
+
method: 'POST',
|
|
41
|
+
headers: { 'Content-Type': 'application/json', ...request.headers },
|
|
42
|
+
body: JSON.stringify(request.body)
|
|
43
|
+
});
|
|
44
|
+
body = await readBody(response, name);
|
|
45
|
+
if (!response.ok) {
|
|
46
|
+
const detail = errorMessage(body);
|
|
47
|
+
const message = `${name} responded with HTTP ${response.status}${detail ? `: ${detail}` : '.'}`;
|
|
48
|
+
return failAll(questions, new JudgyError(message, { status: response.status, cause: body }));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
return failAll(questions, toJudgyError(error, `The ${name} request failed.`));
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
return this.parseAnswers(body, questions);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
return failAll(questions, toJudgyError(error, `Could not read the ${name} response.`));
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Json } from './types.ts';
|
|
2
|
+
export declare const isObject: (value: unknown) => value is Json;
|
|
3
|
+
export declare const object: (value: unknown, label: string) => Json;
|
|
4
|
+
export declare const list: (value: unknown, label: string) => readonly unknown[];
|
|
5
|
+
export declare const finite: (value: unknown, label: string) => number;
|
|
6
|
+
export declare const probability: (value: unknown, label: string) => number;
|
|
7
|
+
/** A score is a level index from 0 to the top level, possibly between two levels. */
|
|
8
|
+
export declare const scoreValue: (value: unknown, levels: number) => number;
|
|
9
|
+
/**
|
|
10
|
+
* Probabilities must sum to 1. Providers round each one, often to two decimals,
|
|
11
|
+
* so every value may be off by half a percent on top of a small base tolerance.
|
|
12
|
+
*/
|
|
13
|
+
export declare const distribution: <T extends readonly number[]>(values: T) => T;
|
|
14
|
+
/** The chosen option, checked against the options the question offered. */
|
|
15
|
+
export declare const option: (value: unknown, options: readonly string[]) => string;
|
|
16
|
+
/** A readable message from a provider error body, whatever its shape. */
|
|
17
|
+
export declare const errorMessage: (body: unknown) => string | undefined;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { JudgyError } from "../errors.js";
|
|
2
|
+
export const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
export const object = (value, label) => {
|
|
4
|
+
if (!isObject(value))
|
|
5
|
+
throw new JudgyError(`Expected ${label} to be an object.`);
|
|
6
|
+
return value;
|
|
7
|
+
};
|
|
8
|
+
export const list = (value, label) => {
|
|
9
|
+
if (!Array.isArray(value))
|
|
10
|
+
throw new JudgyError(`Expected ${label} to be an array.`);
|
|
11
|
+
return value;
|
|
12
|
+
};
|
|
13
|
+
export const finite = (value, label) => {
|
|
14
|
+
if (typeof value !== 'number' || !Number.isFinite(value))
|
|
15
|
+
throw new JudgyError(`Expected ${label} to be a number.`);
|
|
16
|
+
return value;
|
|
17
|
+
};
|
|
18
|
+
export const probability = (value, label) => {
|
|
19
|
+
const number = finite(value, label);
|
|
20
|
+
if (number < 0 || number > 1)
|
|
21
|
+
throw new JudgyError(`Expected ${label} to be between 0 and 1.`);
|
|
22
|
+
return number;
|
|
23
|
+
};
|
|
24
|
+
/** A score is a level index from 0 to the top level, possibly between two levels. */
|
|
25
|
+
export const scoreValue = (value, levels) => {
|
|
26
|
+
const score = finite(value, 'score');
|
|
27
|
+
if (score < 0 || score > levels - 1)
|
|
28
|
+
throw new JudgyError(`Expected the score to be between 0 and ${levels - 1}, got ${score}.`);
|
|
29
|
+
return score;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Probabilities must sum to 1. Providers round each one, often to two decimals,
|
|
33
|
+
* so every value may be off by half a percent on top of a small base tolerance.
|
|
34
|
+
*/
|
|
35
|
+
export const distribution = (values) => {
|
|
36
|
+
const total = values.reduce((sum, value) => sum + value, 0);
|
|
37
|
+
if (Math.abs(total - 1) > 0.01 + values.length * 0.005)
|
|
38
|
+
throw new JudgyError(`Expected the probabilities to sum to 1, got ${total}.`);
|
|
39
|
+
return values;
|
|
40
|
+
};
|
|
41
|
+
/** The chosen option, checked against the options the question offered. */
|
|
42
|
+
export const option = (value, options) => {
|
|
43
|
+
if (typeof value !== 'string' || !options.includes(value))
|
|
44
|
+
throw new JudgyError(`The provider chose ${JSON.stringify(value)}, which is not an option.`);
|
|
45
|
+
return value;
|
|
46
|
+
};
|
|
47
|
+
/** A readable message from a provider error body, whatever its shape. */
|
|
48
|
+
export const errorMessage = (body) => {
|
|
49
|
+
if (typeof body === 'string')
|
|
50
|
+
return body.slice(0, 500) || undefined;
|
|
51
|
+
if (!isObject(body))
|
|
52
|
+
return undefined;
|
|
53
|
+
const { error, detail, errors } = body;
|
|
54
|
+
if (isObject(error) && typeof error.message === 'string')
|
|
55
|
+
return error.message; // OpenAI, Gemini
|
|
56
|
+
if (typeof detail === 'string')
|
|
57
|
+
return detail; // TypeSafe 400
|
|
58
|
+
if (isObject(detail) && typeof detail.message === 'string')
|
|
59
|
+
return detail.message; // TypeSafe 401
|
|
60
|
+
if (detail !== undefined)
|
|
61
|
+
return JSON.stringify(detail); // TypeSafe 422
|
|
62
|
+
if (Array.isArray(errors) && errors.length > 0)
|
|
63
|
+
return JSON.stringify(errors); // Cloudflare
|
|
64
|
+
return undefined;
|
|
65
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The HTTP request a provider wants sent. `body` is serialised as JSON. */
|
|
2
|
+
export interface ProviderRequest {
|
|
3
|
+
readonly url: string;
|
|
4
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
5
|
+
readonly body: unknown;
|
|
6
|
+
}
|
|
7
|
+
/** A JSON object read from a provider response. */
|
|
8
|
+
export type Json = Readonly<Record<string, unknown>>;
|
|
File without changes
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { checkBoolCriteria, checkDescriptions, checkLevels, checkOptions, checkText } from "./validate.js";
|
|
2
|
+
class QuestionKinds {
|
|
3
|
+
#id;
|
|
4
|
+
#prompt;
|
|
5
|
+
constructor(id, prompt) {
|
|
6
|
+
this.#id = id;
|
|
7
|
+
this.#prompt = prompt;
|
|
8
|
+
}
|
|
9
|
+
bool(criteria) {
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
id: this.#id,
|
|
12
|
+
prompt: this.#prompt,
|
|
13
|
+
kind: 'bool',
|
|
14
|
+
...(criteria !== undefined && { criteria: checkBoolCriteria(criteria) })
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
choice(...input) {
|
|
18
|
+
const [first] = input;
|
|
19
|
+
const criteria = input.length === 1 && typeof first === 'object' && first !== null
|
|
20
|
+
? checkDescriptions(first, 'The choice description')
|
|
21
|
+
: undefined;
|
|
22
|
+
const options = checkOptions(criteria ? Object.keys(criteria) : input);
|
|
23
|
+
return Object.freeze({
|
|
24
|
+
id: this.#id,
|
|
25
|
+
prompt: this.#prompt,
|
|
26
|
+
kind: 'choice',
|
|
27
|
+
options: Object.freeze(options),
|
|
28
|
+
...(criteria && { criteria: Object.freeze({ ...criteria }) })
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
score(levels) {
|
|
32
|
+
return Object.freeze({
|
|
33
|
+
id: this.#id,
|
|
34
|
+
prompt: this.#prompt,
|
|
35
|
+
kind: 'score',
|
|
36
|
+
levels: Object.freeze(checkLevels(levels))
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Starts a question: `question(id).ask(prompt)` followed by `.bool()`, `.choice()` or `.score()`. */
|
|
41
|
+
export const question = (id) => {
|
|
42
|
+
checkText(id, 'A question id');
|
|
43
|
+
return { ask: (prompt) => new QuestionKinds(id, checkText(prompt, 'A question prompt')) };
|
|
44
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Answer, BoolAnswer, ChoiceAnswer, ScoreAnswer } from '../answer/types.ts';
|
|
2
|
+
/** Type-only key that links a question to the answer it resolves to. It never exists at runtime. */
|
|
3
|
+
export declare const answerType: unique symbol;
|
|
4
|
+
export interface Question<Id extends string, A extends Answer> {
|
|
5
|
+
readonly id: Id;
|
|
6
|
+
readonly prompt: string;
|
|
7
|
+
readonly kind: 'choice' | 'bool' | 'score';
|
|
8
|
+
readonly [answerType]?: A;
|
|
9
|
+
}
|
|
10
|
+
export interface BoolCriteria {
|
|
11
|
+
readonly true?: string;
|
|
12
|
+
readonly false?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ChoiceQuestion<Id extends string, O extends string> extends Question<Id, ChoiceAnswer<O>> {
|
|
15
|
+
readonly kind: 'choice';
|
|
16
|
+
readonly options: readonly O[];
|
|
17
|
+
readonly criteria?: Readonly<Partial<Record<O, string>>>;
|
|
18
|
+
}
|
|
19
|
+
export interface BoolQuestion<Id extends string> extends Question<Id, BoolAnswer> {
|
|
20
|
+
readonly kind: 'bool';
|
|
21
|
+
readonly criteria?: BoolCriteria;
|
|
22
|
+
}
|
|
23
|
+
export interface ScoreQuestion<Id extends string> extends Question<Id, ScoreAnswer> {
|
|
24
|
+
readonly kind: 'score';
|
|
25
|
+
readonly levels: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
/** Any of the three question kinds, with ids and options left open. */
|
|
28
|
+
export type AnyQuestion = ChoiceQuestion<string, string> | BoolQuestion<string> | ScoreQuestion<string>;
|
|
29
|
+
/** Returned by `question(id)`. */
|
|
30
|
+
export interface QuestionBuilder<Id extends string> {
|
|
31
|
+
ask(prompt: string): QuestionKindBuilder<Id>;
|
|
32
|
+
}
|
|
33
|
+
/** Returned by `.ask(prompt)`. Each method is terminal and returns an immutable question. */
|
|
34
|
+
export interface QuestionKindBuilder<Id extends string> {
|
|
35
|
+
bool(criteria?: BoolCriteria): BoolQuestion<Id>;
|
|
36
|
+
/** Bare option names. */
|
|
37
|
+
choice<O extends string>(...options: O[]): ChoiceQuestion<Id, O>;
|
|
38
|
+
/** Option names with a description each. */
|
|
39
|
+
choice<O extends string>(criteria: Readonly<Record<O, string>>): ChoiceQuestion<Id, O>;
|
|
40
|
+
/** Level descriptions, lowest first. */
|
|
41
|
+
score(levels: readonly string[]): ScoreQuestion<Id>;
|
|
42
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { BoolCriteria } from './types.ts';
|
|
2
|
+
export declare const checkText: (value: unknown, label: string) => string;
|
|
3
|
+
export declare const checkOptions: (options: readonly unknown[]) => string[];
|
|
4
|
+
export declare const checkLevels: (levels: readonly unknown[]) => string[];
|
|
5
|
+
/** Descriptions are optional, but when given they must be strings. */
|
|
6
|
+
export declare const checkDescriptions: <T extends object>(criteria: T, label: string) => T;
|
|
7
|
+
export declare const checkBoolCriteria: (criteria: BoolCriteria) => BoolCriteria;
|