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.
Files changed (54) hide show
  1. package/README.md +195 -7
  2. package/dist/answer/index.d.ts +9 -0
  3. package/dist/answer/index.js +15 -0
  4. package/dist/answer/types.d.ts +37 -0
  5. package/dist/answer/types.js +0 -0
  6. package/dist/client/index.d.ts +3 -0
  7. package/dist/client/index.js +16 -0
  8. package/dist/client/judgy.d.ts +11 -0
  9. package/dist/client/judgy.js +28 -0
  10. package/dist/client/types.d.ts +24 -0
  11. package/dist/client/types.js +0 -0
  12. package/dist/context/image.d.ts +8 -0
  13. package/dist/context/image.js +36 -0
  14. package/dist/context/index.d.ts +3 -0
  15. package/dist/context/index.js +21 -0
  16. package/dist/context/types.d.ts +27 -0
  17. package/dist/context/types.js +0 -0
  18. package/dist/errors.d.ts +7 -0
  19. package/dist/errors.js +10 -0
  20. package/dist/index.d.ts +9 -0
  21. package/dist/index.js +4 -0
  22. package/dist/providers/clef.d.ts +21 -0
  23. package/dist/providers/clef.js +47 -0
  24. package/dist/providers/google.d.ts +13 -0
  25. package/dist/providers/google.js +41 -0
  26. package/dist/providers/jev/answers.d.ts +4 -0
  27. package/dist/providers/jev/answers.js +45 -0
  28. package/dist/providers/jev/index.d.ts +16 -0
  29. package/dist/providers/jev/index.js +43 -0
  30. package/dist/providers/jev/questions.d.ts +14 -0
  31. package/dist/providers/jev/questions.js +35 -0
  32. package/dist/providers/jev/types.d.ts +6 -0
  33. package/dist/providers/jev/types.js +0 -0
  34. package/dist/providers/luna/answers.d.ts +7 -0
  35. package/dist/providers/luna/answers.js +63 -0
  36. package/dist/providers/luna/index.d.ts +12 -0
  37. package/dist/providers/luna/index.js +18 -0
  38. package/dist/providers/luna/questions.d.ts +10 -0
  39. package/dist/providers/luna/questions.js +43 -0
  40. package/dist/providers/provider.d.ts +27 -0
  41. package/dist/providers/provider.js +61 -0
  42. package/dist/providers/read.d.ts +17 -0
  43. package/dist/providers/read.js +65 -0
  44. package/dist/providers/types.d.ts +8 -0
  45. package/dist/providers/types.js +0 -0
  46. package/dist/question/index.d.ts +3 -0
  47. package/dist/question/index.js +44 -0
  48. package/dist/question/types.d.ts +42 -0
  49. package/dist/question/types.js +0 -0
  50. package/dist/question/validate.d.ts +7 -0
  51. package/dist/question/validate.js +46 -0
  52. package/dist/types.d.ts +5 -0
  53. package/dist/types.js +0 -0
  54. package/package.json +34 -6
package/README.md CHANGED
@@ -1,25 +1,213 @@
1
1
  # 💅 judgy
2
2
 
3
- A tiny, tree-shakable router for System 1 decision models. Quick to judge, by design.
3
+ A tiny, zero-dependency router for System 1 decision models. Quick to judge, by design.
4
4
 
5
5
  [![npm](https://img.shields.io/npm/v/judgy?logo=npm)](https://www.npmjs.com/package/judgy)
6
6
  [![MIT license](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
7
7
 
8
- > **Placeholder release.** This version reserves the name and ships no code yet. The first working release is in progress.
9
-
10
8
  ## What it is
11
9
 
12
10
  System 1 models are fast, decision-focused models: they pick, classify and decide instead of generating text. Every provider ships its own SDK and request shape, so you end up rewriting the same glue code for each one.
13
11
 
14
- `judgy` is one standard interface in front of all of them. Declare the decision once and route it to whichever provider you choose, without writing a new integration each time.
12
+ `judgy` is one standard interface in front of all of them. Build a context, ask typed questions, and run them on whichever provider you choose, without writing a new integration each time.
15
13
 
16
14
  - **Decision models only.** It is not a wrapper for generative LLMs.
17
- - **Tiny and tree-shakable.** You ship only the providers you import.
18
- - **TypeScript first.**
15
+ - **Tiny, zero dependencies.** No vendor SDKs. Every provider is a plain `fetch` call.
16
+ - **TypeScript first.** Answers are typed from the questions you ask.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install judgy
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { createJudgy, context, question } from 'judgy';
28
+
29
+ const key = process.env.TYPESAFE_AI_API_KEY;
30
+ if (!key) throw new Error('Set TYPESAFE_AI_API_KEY to your TypeSafe API key.');
31
+
32
+ const judgy = createJudgy().jev(key, 'jev-latest');
33
+
34
+ const ctx = context().text('Refund request: the item arrived broken.');
35
+ const fraud = question('fraud').ask('Does this look fraudulent?').bool();
36
+
37
+ const answer = await judgy.run(ctx, fraud);
38
+
39
+ if (answer.ok) {
40
+ answer.value; // boolean
41
+ answer.probability; // how likely the answer is true, 0 to 1
42
+ }
43
+ ```
44
+
45
+ ## Client
46
+
47
+ Pick a provider and pass its API key and model. The call returns a ready client. Clef runs on Cloudflare Workers AI, so it also takes your Cloudflare account id.
48
+
49
+ ```ts
50
+ createJudgy().jev(key, model);
51
+ createJudgy().luna(key, model);
52
+ createJudgy().google(key, model);
53
+ createJudgy().clef(key, model, accountId);
54
+ ```
55
+
56
+ | Provider | Call | Models |
57
+ | ---------------------------- | ------------------------------ | ----------------------------------------- |
58
+ | Jev (TypeSafe) | `.jev(key, model)` | `jev-latest`, `jev-preview`, `jev-1.14.0` |
59
+ | GPT Luna decisions (OpenAI) | `.luna(key, model)` | `gpt-6-luna` |
60
+ | Google decisions (Gemini) | `.google(key, model)` | `gemini-decision-1` |
61
+ | Clef (Cloudflare Workers AI) | `.clef(key, model, accountId)` | `clef`, `clef-flash` |
62
+
63
+ Every client exposes the same `run` method, so switching provider is a one-line change.
64
+
65
+ `createJudgy()` takes one optional setting: your own `fetch`, for tests, proxies or logging. It defaults to the global `fetch`.
66
+
67
+ ```ts
68
+ createJudgy({ fetch: myFetch }).jev(key, model);
69
+ ```
70
+
71
+ ## Context
72
+
73
+ The context is what the model judges. `.text()` and `.image()` can be repeated.
74
+
75
+ ```ts
76
+ const ctx = context().text(ticket).image(photoBase64);
77
+ ```
78
+
79
+ Images are base64 strings, PNG or JPEG. judgy reads the format from the data, so there is nothing else to pass.
80
+
81
+ All four providers accept images. When an image goes past a provider's documented count or size limit, judgy logs a `console.error`, leaves that image out and still runs the questions with the rest of the context:
82
+
83
+ - Clef: at most four images, 4 MiB each and 8 MiB in all. It sees them before the text.
84
+ - Jev: at most 16 MiB per image. TypeSafe still calls image support a preview, and judgy opts in for you.
85
+
86
+ judgy can't know every model's rules in advance. A provider that rejects an image for another reason, such as its pixel dimensions, fails the whole request.
87
+
88
+ ## Questions
89
+
90
+ A question has an id, a prompt and one of three kinds. The kind is the last call and returns an immutable question. Each kind takes criteria that tell the model what its answers mean.
91
+
92
+ ```ts
93
+ const fraud = question('fraud').ask('Does this look fraudulent?').bool({
94
+ true: 'The photo looks staged or reused.',
95
+ false: 'Nothing suspicious.'
96
+ });
97
+
98
+ const action = question('action').ask('What should we do?').choice({
99
+ approve: 'The damage is clear and the order is recent.',
100
+ reject: 'No damage is visible, or the claim is out of policy.',
101
+ escalate: 'The evidence is unclear.'
102
+ });
103
+
104
+ const urgency = question('urgency')
105
+ .ask('How urgent is this?')
106
+ .score(['Can wait a week.', 'Should be handled today.', 'Needs a reply within the hour.']);
107
+ ```
108
+
109
+ | Kind | Criteria | Answer value |
110
+ | ------------------- | ------------------------------------------- | ----------------------------------------- |
111
+ | `.bool(criteria?)` | optional descriptions of `true` and `false` | `boolean`, true from a probability of 0.5 |
112
+ | `.choice(criteria)` | 2 to 255 options, each with a description | one of the options |
113
+ | `.score(levels)` | 2 to 10 level descriptions, lowest first | level number from 0, can fall between two |
114
+
115
+ Option names have no surrounding spaces and at most 128 characters, the strictest rule among the providers, so a question works on all of them. Criteria are optional for `bool` and `choice`. `.bool()` works on its own, and `.choice("approve", "reject", "escalate")` takes bare option names.
116
+
117
+ ## Run
118
+
119
+ `run` takes a context and one question, and resolves to its answer. Check `ok` before reading the value.
120
+
121
+ ```ts
122
+ const answer = await judgy.run(ctx, fraud);
123
+
124
+ if (answer.ok) {
125
+ answer.value; // boolean
126
+ answer.probability; // how likely the answer is true, 0 to 1
127
+ } else {
128
+ answer.error; // JudgyError
129
+ }
130
+ ```
131
+
132
+ Pass several questions to get a record keyed by question id.
133
+
134
+ ```ts
135
+ const answers = await judgy.run(ctx, [action, fraud, urgency]);
136
+
137
+ if (answers.action.ok) answers.action.value; // "approve" | "reject" | "escalate"
138
+ if (answers.fraud.ok) answers.fraud.value; // boolean
139
+ if (answers.urgency.ok) answers.urgency.value; // number, 0 to 2 here
140
+ ```
141
+
142
+ When the array isn't written out as a literal, TypeScript can't know which ids it holds, so every key in the result is optional.
143
+
144
+ Questions in one run are independent. Each sees the context, never another question's answer. All of them travel in a single request.
145
+
146
+ ### Failures
147
+
148
+ `run` does not reject when a provider fails. The failure comes back as the answer.
149
+
150
+ - If the request fails, every answer has `ok: false` and the same `error`.
151
+ - If the provider declines one question, only that answer fails. Of the four, only GPT Luna declines single questions.
152
+ - If one answer comes back malformed, only that answer fails.
153
+
154
+ `run` throws only for mistakes in your code, always before any request is sent. Ids must be unique within a run, and a run can't hold more questions than its provider takes: 64 for Clef, 400 for GPT Luna and 1,000 for Google. Either mistake throws a `JudgyError`.
155
+
156
+ ## Types
157
+
158
+ ```ts
159
+ interface Question<Id extends string, A extends Answer> {
160
+ readonly id: Id;
161
+ readonly prompt: string;
162
+ readonly kind: 'choice' | 'bool' | 'score';
163
+ }
164
+
165
+ interface ChoiceQuestion<Id extends string, O extends string> extends Question<
166
+ Id,
167
+ ChoiceAnswer<O>
168
+ > {
169
+ readonly options: readonly O[];
170
+ readonly criteria?: Readonly<Partial<Record<O, string>>>;
171
+ }
172
+ interface BoolQuestion<Id extends string> extends Question<Id, BoolAnswer> {
173
+ readonly criteria?: { readonly true?: string; readonly false?: string };
174
+ }
175
+ interface ScoreQuestion<Id extends string> extends Question<Id, ScoreAnswer> {
176
+ readonly levels: readonly string[]; // lowest first
177
+ }
178
+
179
+ interface Ok<T> {
180
+ readonly ok: true;
181
+ readonly value: T;
182
+ readonly raw: unknown; // the provider's answer, untouched
183
+ }
184
+ interface Failed {
185
+ readonly ok: false;
186
+ readonly error: JudgyError;
187
+ }
188
+
189
+ interface BoolOk extends Ok<boolean> {
190
+ readonly probability: number; // probability of true
191
+ }
192
+ interface ChoiceOk<O extends string> extends Ok<O> {
193
+ readonly confidence: number;
194
+ readonly probabilities: Readonly<Record<O, number>>;
195
+ }
196
+ interface ScoreOk extends Ok<number> {
197
+ readonly confidence: number;
198
+ readonly probabilities: readonly number[]; // one per level
199
+ }
200
+
201
+ type BoolAnswer = BoolOk | Failed;
202
+ type ChoiceAnswer<O extends string> = ChoiceOk<O> | Failed;
203
+ type ScoreAnswer = ScoreOk | Failed;
204
+
205
+ type Answer = BoolAnswer | ChoiceAnswer<string> | ScoreAnswer;
206
+ ```
19
207
 
20
208
  ## Status
21
209
 
22
- `0.0.1` is a name reservation. Watch or star the [GitHub repository](https://github.com/feuersteiner/system1) to follow progress.
210
+ `0.1.0` is the first working release. The API may still change before `1.0`. Watch or star the [GitHub repository](https://github.com/feuersteiner/judgy) to follow progress.
23
211
 
24
212
  ## License
25
213
 
@@ -0,0 +1,9 @@
1
+ import { JudgyError } from '../errors.ts';
2
+ import type { AnyQuestion } from '../question/types.ts';
3
+ import type { Answer, Failed } from './types.ts';
4
+ export declare const failed: (error: JudgyError) => Failed;
5
+ export declare const toJudgyError: (error: unknown, message: string) => JudgyError;
6
+ /** The same failure for every question, used when the whole request fails. */
7
+ export declare const failAll: (questions: readonly AnyQuestion[], error: JudgyError) => Record<string, Answer>;
8
+ /** Reads each answer on its own, so a declined or malformed answer fails only its question. */
9
+ export declare const settle: (questions: readonly AnyQuestion[], read: (question: AnyQuestion, index: number) => Answer) => Record<string, Answer>;
@@ -0,0 +1,15 @@
1
+ import { JudgyError } from "../errors.js";
2
+ export const failed = (error) => Object.freeze({ ok: false, error });
3
+ export const toJudgyError = (error, message) => error instanceof JudgyError ? error : new JudgyError(message, { cause: error });
4
+ /** The same failure for every question, used when the whole request fails. */
5
+ export const failAll = (questions, error) => Object.fromEntries(questions.map((question) => [question.id, failed(error)]));
6
+ /** Reads each answer on its own, so a declined or malformed answer fails only its question. */
7
+ export const settle = (questions, read) => Object.fromEntries(questions.map((question, index) => {
8
+ try {
9
+ return [question.id, read(question, index)];
10
+ }
11
+ catch (error) {
12
+ const message = `Could not read the answer to "${question.id}".`;
13
+ return [question.id, failed(toJudgyError(error, message))];
14
+ }
15
+ }));
@@ -0,0 +1,37 @@
1
+ import type { JudgyError } from '../errors.ts';
2
+ import type { AnyQuestion, BoolQuestion, ChoiceQuestion, ScoreQuestion } from '../question/types.ts';
3
+ export interface Ok<T> {
4
+ readonly ok: true;
5
+ readonly value: T;
6
+ readonly raw: unknown;
7
+ }
8
+ export interface Failed {
9
+ readonly ok: false;
10
+ readonly error: JudgyError;
11
+ }
12
+ export interface BoolOk extends Ok<boolean> {
13
+ readonly probability: number;
14
+ }
15
+ export interface ChoiceOk<O extends string> extends Ok<O> {
16
+ readonly confidence: number;
17
+ readonly probabilities: Readonly<Record<O, number>>;
18
+ }
19
+ export interface ScoreOk extends Ok<number> {
20
+ readonly confidence: number;
21
+ readonly probabilities: readonly number[];
22
+ }
23
+ export type BoolAnswer = BoolOk | Failed;
24
+ export type ChoiceAnswer<O extends string> = ChoiceOk<O> | Failed;
25
+ export type ScoreAnswer = ScoreOk | Failed;
26
+ export type Answer = BoolAnswer | ChoiceAnswer<string> | ScoreAnswer;
27
+ /** The answer type a given question resolves to. */
28
+ export type AnswerOf<Q extends AnyQuestion> = Q extends ChoiceQuestion<string, infer O extends string> ? ChoiceAnswer<O> : Q extends BoolQuestion<string> ? BoolAnswer : Q extends ScoreQuestion<string> ? ScoreAnswer : never;
29
+ /** Answers keyed by each question's id. */
30
+ export type AnswerRecord<Qs extends readonly AnyQuestion[]> = {
31
+ readonly [Q in Qs[number] as Q['id']]: AnswerOf<Q>;
32
+ };
33
+ /**
34
+ * Answers for several questions. A literal list or tuple fixes which ids come back.
35
+ * Any other array may hold only some of its possible questions, so each key is optional.
36
+ */
37
+ export type AnswersOf<Qs extends readonly AnyQuestion[]> = number extends Qs['length'] ? Partial<AnswerRecord<Qs>> : AnswerRecord<Qs>;
File without changes
@@ -0,0 +1,3 @@
1
+ import type { JudgyFactory, JudgyOptions } from './types.ts';
2
+ /** Entry point: `createJudgy().jev(key, model)` returns a ready client. */
3
+ export declare const createJudgy: (options?: JudgyOptions) => JudgyFactory;
@@ -0,0 +1,16 @@
1
+ import { ClefProvider } from "../providers/clef.js";
2
+ import { GoogleProvider } from "../providers/google.js";
3
+ import { JevProvider } from "../providers/jev/index.js";
4
+ import { LunaProvider } from "../providers/luna/index.js";
5
+ import { JudgyClient } from "./judgy.js";
6
+ /** Entry point: `createJudgy().jev(key, model)` returns a ready client. */
7
+ export const createJudgy = (options = {}) => {
8
+ // Looked up on each call, so a global `fetch` replaced later is still used.
9
+ const fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
10
+ return {
11
+ jev: (key, model) => new JudgyClient(new JevProvider(key, model, fetch)),
12
+ luna: (key, model) => new JudgyClient(new LunaProvider(key, model, fetch)),
13
+ google: (key, model) => new JudgyClient(new GoogleProvider(key, model, fetch)),
14
+ clef: (key, model, accountId) => new JudgyClient(new ClefProvider(key, model, accountId, fetch))
15
+ };
16
+ };
@@ -0,0 +1,11 @@
1
+ import type { AnswerOf, AnswersOf } from '../answer/types.ts';
2
+ import type { Context } from '../context/types.ts';
3
+ import type { Provider } from '../providers/provider.ts';
4
+ import type { AnyQuestion } from '../question/types.ts';
5
+ import type { Judgy } from './types.ts';
6
+ export declare class JudgyClient implements Judgy {
7
+ #private;
8
+ constructor(provider: Provider);
9
+ run<Q extends AnyQuestion>(context: Context, question: Q): Promise<AnswerOf<Q>>;
10
+ run<const Qs extends readonly AnyQuestion[]>(context: Context, questions: Qs): Promise<AnswersOf<Qs>>;
11
+ }
@@ -0,0 +1,28 @@
1
+ import { JudgyError } from "../errors.js";
2
+ const isList = (input) => Array.isArray(input);
3
+ /** Mistakes in the caller's code throw before any request is sent. */
4
+ const checkQuestions = (questions, provider) => {
5
+ if (questions.length === 0)
6
+ throw new JudgyError('run() needs at least one question.');
7
+ if (questions.length > provider.maxQuestions)
8
+ throw new JudgyError(`${provider.name} takes at most ${provider.maxQuestions} questions per run, got ${questions.length}.`);
9
+ const seen = new Set();
10
+ for (const { id } of questions) {
11
+ if (seen.has(id))
12
+ throw new JudgyError(`Question ids must be unique within a run; "${id}" appears twice.`);
13
+ seen.add(id);
14
+ }
15
+ };
16
+ export class JudgyClient {
17
+ #provider;
18
+ constructor(provider) {
19
+ this.#provider = provider;
20
+ }
21
+ async run(context, input) {
22
+ // A copy, so reordering the caller's array mid-flight can't move answers between questions.
23
+ const questions = isList(input) ? [...input] : [input];
24
+ checkQuestions(questions, this.#provider);
25
+ const answers = await this.#provider.run(context, questions);
26
+ return isList(input) ? answers : answers[input.id];
27
+ }
28
+ }
@@ -0,0 +1,24 @@
1
+ import type { AnswerOf, AnswersOf } from '../answer/types.ts';
2
+ import type { Context } from '../context/types.ts';
3
+ import type { AnyQuestion } from '../question/types.ts';
4
+ /**
5
+ * The call signature of `fetch`. Narrower than `typeof fetch` on purpose: some runtimes add
6
+ * static members to the global (Bun adds `fetch.preconnect`), which a hand-written fake lacks.
7
+ */
8
+ export type Fetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
9
+ export interface JudgyOptions {
10
+ /** Your own `fetch`, for tests, proxies or logging. Defaults to the global `fetch`. */
11
+ readonly fetch?: Fetch;
12
+ }
13
+ /** A ready client, bound to one provider and model. */
14
+ export interface Judgy {
15
+ run<Q extends AnyQuestion>(context: Context, question: Q): Promise<AnswerOf<Q>>;
16
+ run<const Qs extends readonly AnyQuestion[]>(context: Context, questions: Qs): Promise<AnswersOf<Qs>>;
17
+ }
18
+ /** Returned by `createJudgy()`. Each method picks a provider and returns a client. */
19
+ export interface JudgyFactory {
20
+ jev(key: string, model: string): Judgy;
21
+ luna(key: string, model: string): Judgy;
22
+ google(key: string, model: string): Judgy;
23
+ clef(key: string, model: string, accountId: string): Judgy;
24
+ }
File without changes
@@ -0,0 +1,8 @@
1
+ import type { Context, ImageFormat, ImageLimits, ImagePart } from './types.ts';
2
+ /** Reads the image format from the first bytes of a base64 string. `undefined` when it is neither PNG nor JPEG. */
3
+ export declare const detectImageFormat: (base64: string) => ImageFormat | undefined;
4
+ export declare const imagePart: (base64: string) => ImagePart;
5
+ export declare const mimeType: (part: ImagePart) => string;
6
+ export declare const dataUrl: (part: ImagePart) => string;
7
+ /** Leaves out, in order, the images past a provider's documented count and size limits, and says so. */
8
+ export declare const fitImages: (context: Context, limits: ImageLimits, provider: string) => Context;
@@ -0,0 +1,36 @@
1
+ import { JudgyError } from "../errors.js";
2
+ const signatures = { png: 'iVBORw0KGgo', jpeg: '/9j/' };
3
+ const mimeTypes = { png: 'image/png', jpeg: 'image/jpeg' };
4
+ const formats = ['png', 'jpeg'];
5
+ /** Standard base64 with padding and no whitespace, which every provider accepts. */
6
+ const isBase64 = (value) => value.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(value);
7
+ /** Reads the image format from the first bytes of a base64 string. `undefined` when it is neither PNG nor JPEG. */
8
+ export const detectImageFormat = (base64) => formats.find((format) => base64.startsWith(signatures[format]));
9
+ export const imagePart = (base64) => {
10
+ const format = typeof base64 === 'string' && isBase64(base64) ? detectImageFormat(base64) : undefined;
11
+ if (!format)
12
+ throw new JudgyError('context().image() needs a base64 string holding a PNG or JPEG.');
13
+ return Object.freeze({ type: 'image', base64, format });
14
+ };
15
+ export const mimeType = (part) => mimeTypes[part.format];
16
+ export const dataUrl = (part) => `data:${mimeType(part)};base64,${part.base64}`;
17
+ const decodedBytes = ({ base64 }) => (base64.length / 4) * 3 - (base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0);
18
+ /** Leaves out, in order, the images past a provider's documented count and size limits, and says so. */
19
+ export const fitImages = (context, limits, provider) => {
20
+ const { count = Infinity, bytes = Infinity, totalBytes = Infinity } = limits;
21
+ let kept = 0;
22
+ let total = 0;
23
+ const parts = context.parts.filter((part) => {
24
+ if (part.type === 'text')
25
+ return true;
26
+ const size = decodedBytes(part);
27
+ if (kept >= count || size > bytes || total + size > totalBytes) {
28
+ console.error(`judgy: an image goes past ${provider}'s image limits, so it was left out.`);
29
+ return false;
30
+ }
31
+ kept += 1;
32
+ total += size;
33
+ return true;
34
+ });
35
+ return { parts };
36
+ };
@@ -0,0 +1,3 @@
1
+ import type { ContextBuilder } from './types.ts';
2
+ /** Starts a context: `context().text(...).image(...)`. */
3
+ export declare const context: () => ContextBuilder;
@@ -0,0 +1,21 @@
1
+ import { JudgyError } from "../errors.js";
2
+ import { imagePart } from "./image.js";
3
+ /** Immutable: every call returns a new builder with one more part. */
4
+ class ContextChain {
5
+ parts;
6
+ constructor(parts) {
7
+ this.parts = Object.freeze(parts);
8
+ Object.freeze(this);
9
+ }
10
+ text(text) {
11
+ if (typeof text !== 'string' || text.length === 0)
12
+ throw new JudgyError('context().text() needs a non-empty string.');
13
+ const part = Object.freeze({ type: 'text', text });
14
+ return new ContextChain([...this.parts, part]);
15
+ }
16
+ image(base64) {
17
+ return new ContextChain([...this.parts, imagePart(base64)]);
18
+ }
19
+ }
20
+ /** Starts a context: `context().text(...).image(...)`. */
21
+ export const context = () => new ContextChain([]);
@@ -0,0 +1,27 @@
1
+ export type ImageFormat = 'png' | 'jpeg';
2
+ export interface TextPart {
3
+ readonly type: 'text';
4
+ readonly text: string;
5
+ }
6
+ export interface ImagePart {
7
+ readonly type: 'image';
8
+ readonly base64: string;
9
+ readonly format: ImageFormat;
10
+ }
11
+ export type ContextPart = TextPart | ImagePart;
12
+ /** What the model judges: text and images, in the order they were added. */
13
+ export interface Context {
14
+ readonly parts: readonly ContextPart[];
15
+ }
16
+ /** A provider's documented image limits. Sizes are decoded bytes. */
17
+ export interface ImageLimits {
18
+ readonly count?: number;
19
+ readonly bytes?: number;
20
+ readonly totalBytes?: number;
21
+ }
22
+ /** Returned by `context()`. It is itself a `Context`, so it goes straight into `run`. */
23
+ export interface ContextBuilder extends Context {
24
+ text(text: string): ContextBuilder;
25
+ /** A base64 string holding a PNG or JPEG. The format is read from the data. */
26
+ image(base64: string): ContextBuilder;
27
+ }
File without changes
@@ -0,0 +1,7 @@
1
+ import type { JudgyErrorOptions } from './types.ts';
2
+ /** The one error type judgy throws or returns inside a failed answer. */
3
+ export declare class JudgyError extends Error {
4
+ /** HTTP status of the provider response, when the failure came from one. */
5
+ readonly status?: number;
6
+ constructor(message: string, options?: JudgyErrorOptions);
7
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,10 @@
1
+ /** The one error type judgy throws or returns inside a failed answer. */
2
+ export class JudgyError extends Error {
3
+ /** HTTP status of the provider response, when the failure came from one. */
4
+ status;
5
+ constructor(message, options) {
6
+ super(message, { cause: options?.cause });
7
+ this.name = 'JudgyError';
8
+ this.status = options?.status;
9
+ }
10
+ }
@@ -0,0 +1,9 @@
1
+ export { createJudgy } from './client/index.ts';
2
+ export { context } from './context/index.ts';
3
+ export { question } from './question/index.ts';
4
+ export { JudgyError } from './errors.ts';
5
+ export type * from './answer/types.ts';
6
+ export type * from './client/types.ts';
7
+ export type * from './context/types.ts';
8
+ export type * from './question/types.ts';
9
+ export type * from './types.ts';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createJudgy } from "./client/index.js";
2
+ export { context } from "./context/index.js";
3
+ export { question } from "./question/index.js";
4
+ export { JudgyError } from "./errors.js";
@@ -0,0 +1,21 @@
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 { Fetch } from '../client/types.ts';
5
+ import type { AnyQuestion } from '../question/types.ts';
6
+ import type { ProviderRequest } from './types.ts';
7
+ /**
8
+ * Clef, on Cloudflare Workers AI: https://developers.cloudflare.com/workers-ai/models/clef/
9
+ *
10
+ * Clef speaks the System One format inside Cloudflare's `{ result, success, errors }` envelope.
11
+ * Images go in a separate `images` list, which the model sees before the text.
12
+ */
13
+ export declare class ClefProvider extends Provider {
14
+ readonly name = "clef";
15
+ readonly maxQuestions = 64;
16
+ /** Cloudflare account id, part of the request URL. */
17
+ protected readonly accountId: string;
18
+ constructor(key: string, model: string, accountId: string, fetch: Fetch);
19
+ protected buildRequest(context: Context, questions: readonly AnyQuestion[]): ProviderRequest;
20
+ protected parseAnswers(body: unknown, questions: readonly AnyQuestion[]): Record<string, Answer>;
21
+ }
@@ -0,0 +1,47 @@
1
+ import { dataUrl, fitImages } from "../context/image.js";
2
+ import { JudgyError } from "../errors.js";
3
+ import { errorMessage, object } from "./read.js";
4
+ import { Provider } from "./provider.js";
5
+ import { systemOneAnswers } from "./jev/answers.js";
6
+ import { systemOneQuestions } from "./jev/questions.js";
7
+ const mebibyte = 1024 * 1024;
8
+ /** Workers AI takes at most four images per Clef request, 4 MiB each and 8 MiB in all. */
9
+ const imageLimits = { count: 4, bytes: 4 * mebibyte, totalBytes: 8 * mebibyte };
10
+ /**
11
+ * Clef, on Cloudflare Workers AI: https://developers.cloudflare.com/workers-ai/models/clef/
12
+ *
13
+ * Clef speaks the System One format inside Cloudflare's `{ result, success, errors }` envelope.
14
+ * Images go in a separate `images` list, which the model sees before the text.
15
+ */
16
+ export class ClefProvider extends Provider {
17
+ name = 'clef';
18
+ maxQuestions = 64;
19
+ /** Cloudflare account id, part of the request URL. */
20
+ accountId;
21
+ constructor(key, model, accountId, fetch) {
22
+ super(key, model, fetch);
23
+ this.accountId = accountId;
24
+ }
25
+ buildRequest(context, questions) {
26
+ const { parts } = fitImages(context, imageLimits, this.name);
27
+ const texts = parts.filter((part) => part.type === 'text');
28
+ const images = parts.filter((part) => part.type === 'image');
29
+ const account = encodeURIComponent(this.accountId);
30
+ return {
31
+ url: `https://api.cloudflare.com/client/v4/accounts/${account}/ai/run/@cf/cloudflare/${encodeURIComponent(this.model)}`,
32
+ headers: { Authorization: `Bearer ${this.key}` },
33
+ body: {
34
+ model: this.model,
35
+ state: texts.length === 1 ? texts[0]?.text : texts.map((part) => part.text),
36
+ questions: systemOneQuestions(questions, 'typesafe'),
37
+ ...(images.length > 0 && { images: images.map(dataUrl) })
38
+ }
39
+ };
40
+ }
41
+ parseAnswers(body, questions) {
42
+ const envelope = object(body, 'the response');
43
+ if (envelope.success === false)
44
+ throw new JudgyError(`clef failed: ${errorMessage(envelope) ?? 'no reason given'}.`);
45
+ return systemOneAnswers(object(envelope.result, 'result').answers, questions);
46
+ }
47
+ }
@@ -0,0 +1,13 @@
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
+ /** Google decisions, on the Gemini Decisions API: https://ai.google.dev/gemini-api/docs/decisions */
7
+ export declare class GoogleProvider extends Provider {
8
+ readonly name = "google";
9
+ readonly maxQuestions = 1000;
10
+ protected buildRequest(context: Context, questions: readonly AnyQuestion[]): ProviderRequest;
11
+ /** A request blocked by safety filters can come back as a 200 with `prompt_feedback`. */
12
+ protected parseAnswers(body: unknown, questions: readonly AnyQuestion[]): Record<string, Answer>;
13
+ }
@@ -0,0 +1,41 @@
1
+ import { mimeType } from "../context/image.js";
2
+ import { JudgyError } from "../errors.js";
3
+ import { isObject, object } from "./read.js";
4
+ import { Provider } from "./provider.js";
5
+ import { systemOneAnswers } from "./jev/answers.js";
6
+ import { systemOneQuestions } from "./jev/questions.js";
7
+ /** Gemini joins adjacent text blocks with no separator, so later ones start on a new paragraph. */
8
+ const input = ({ parts }) => {
9
+ const [only] = parts;
10
+ if (parts.length === 1 && only?.type === 'text')
11
+ return only.text;
12
+ return parts.map((part, index) => part.type === 'text'
13
+ ? { type: 'text', text: parts[index - 1]?.type === 'text' ? `\n\n${part.text}` : part.text }
14
+ : { type: 'image', data: part.base64, mime_type: mimeType(part) });
15
+ };
16
+ /** Google decisions, on the Gemini Decisions API: https://ai.google.dev/gemini-api/docs/decisions */
17
+ export class GoogleProvider extends Provider {
18
+ name = 'google';
19
+ maxQuestions = 1000;
20
+ buildRequest(context, questions) {
21
+ return {
22
+ url: 'https://generativelanguage.googleapis.com/v1beta/decisions',
23
+ headers: { 'x-goog-api-key': this.key },
24
+ body: {
25
+ model: this.model,
26
+ input: input(context),
27
+ questions: systemOneQuestions(questions, 'google')
28
+ }
29
+ };
30
+ }
31
+ /** A request blocked by safety filters can come back as a 200 with `prompt_feedback`. */
32
+ parseAnswers(body, questions) {
33
+ const response = object(body, 'the response');
34
+ const feedback = response.prompt_feedback;
35
+ if (isObject(feedback) && feedback.block_reason) {
36
+ const reason = feedback.block_reason_message ?? feedback.block_reason;
37
+ throw new JudgyError(`google blocked the request: ${String(reason)}`);
38
+ }
39
+ return systemOneAnswers(response.answers, questions);
40
+ }
41
+ }