@xsai/decide 0.0.0-stage → 1.0.0-beta.1

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.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Moeru AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @xsai/decide
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <!-- automd:file src="/docs/snippets/decide.md" -->
4
+
5
+ ```sh
6
+ pnpm add @xsai/decide
7
+ ```
8
+
9
+ ```ts
10
+ import { decide, decisions } from '@xsai/decide'
11
+
12
+ const model = decisions({
13
+ apiKey: process.env.OPENAI_API_KEY,
14
+ baseURL: 'https://api.openai.com/v1/',
15
+ model: 'gpt-6-luna',
16
+ })
17
+
18
+ const { answers } = await decide(model, {
19
+ input: 'The package arrived with a broken screen.',
20
+ questions: {
21
+ damaged: { instructions: 'Does the customer report a damaged item?', type: 'boolean' },
22
+ },
23
+ })
24
+ console.log(answers.damaged.probability)
25
+ ```
26
+
27
+ <!-- /automd -->
28
+
29
+ Read the [documentation](https://xsai.js.org/decide).
@@ -0,0 +1,129 @@
1
+ import { Promisable, XSAIError, HttpOptions } from '@xsai/shared';
2
+ import { LanguageModelOptions, LanguageModel } from '@xsai/text';
3
+
4
+ interface DecideResult<Q extends DecisionQuestions> extends Omit<DecisionModelResult, 'answers'> {
5
+ answers: {
6
+ readonly [K in keyof Q]: DecisionAnswerFor<Q[K]>;
7
+ };
8
+ }
9
+ type DecisionAnswer = DecisionBooleanAnswer | DecisionChoiceAnswer | DecisionScoreAnswer;
10
+ type DecisionAnswerFor<Q extends DecisionQuestion> = Q extends {
11
+ type: 'choice';
12
+ } ? DecisionChoiceAnswer<Q['choices'][number]['value']> : Q extends {
13
+ type: 'score';
14
+ } ? DecisionScoreAnswer : DecisionBooleanAnswer;
15
+ interface DecisionBooleanAnswer {
16
+ /** The probability of true. */
17
+ probability: number;
18
+ type: 'boolean';
19
+ }
20
+ interface DecisionChoice {
21
+ description?: string;
22
+ value: string;
23
+ }
24
+ interface DecisionChoiceAnswer<V extends string = string> {
25
+ choice: V;
26
+ confidence?: number;
27
+ probabilities?: readonly {
28
+ probability: number;
29
+ value: V;
30
+ }[];
31
+ type: 'choice';
32
+ }
33
+ type DecisionContent = Record<string, unknown> | string;
34
+ type DecisionModel = (options: DecisionModelOptions) => Promisable<DecisionModelResult>;
35
+ interface DecisionModelOptions {
36
+ input: DecisionContent;
37
+ providerOptions?: DecisionModelProviderOptions;
38
+ questions: DecisionQuestions;
39
+ signal?: AbortSignal;
40
+ }
41
+ interface DecisionModelProviderOptions {
42
+ }
43
+ interface DecisionModelResult {
44
+ answers: Readonly<Record<string, DecisionAnswer | DecisionRefusal>>;
45
+ usage: DecisionUsage;
46
+ }
47
+ type DecisionQuestion = {
48
+ readonly choices: readonly DecisionChoice[];
49
+ readonly instructions: DecisionContent;
50
+ readonly type: 'choice';
51
+ } | {
52
+ readonly instructions: DecisionContent;
53
+ readonly levels: readonly DecisionScoreLevel[];
54
+ readonly type: 'score';
55
+ } | {
56
+ readonly instructions: DecisionContent;
57
+ readonly type: 'boolean';
58
+ };
59
+ type DecisionQuestions = Readonly<Record<string, DecisionQuestion>>;
60
+ interface DecisionRefusal {
61
+ type: 'refusal';
62
+ }
63
+ interface DecisionScoreAnswer {
64
+ confidence?: number;
65
+ probabilities?: Readonly<Record<string, number>>;
66
+ score: number;
67
+ type: 'score';
68
+ }
69
+ interface DecisionScoreLevel {
70
+ readonly description?: DecisionContent;
71
+ readonly label: string;
72
+ }
73
+ interface DecisionUsage {
74
+ inputTokens?: number;
75
+ outputTokens?: number;
76
+ totalTokens?: number;
77
+ }
78
+
79
+ declare module '@xsai/shared' {
80
+ interface XSAIErrorCauseMap {
81
+ 'decision-refusal': undefined;
82
+ }
83
+ }
84
+ declare class DecisionRefusalError extends XSAIError<'decision-refusal'> {
85
+ readonly questionIds: readonly string[];
86
+ constructor(questionIds: readonly string[]);
87
+ }
88
+ declare const decide: <const Q extends DecisionQuestions>(model: DecisionModel, options: Omit<DecisionModelOptions, "questions"> & {
89
+ questions: Q;
90
+ }) => Promise<DecideResult<Q>>;
91
+
92
+ type OpenAIDecisionsInput = readonly {
93
+ content: readonly ({
94
+ detail?: 'auto' | 'high' | 'low' | 'original' | null;
95
+ image_url: string;
96
+ type: 'input_image';
97
+ } | {
98
+ text: string;
99
+ type: 'input_text';
100
+ })[] | string;
101
+ role: 'user';
102
+ type?: 'message';
103
+ }[] | string;
104
+ declare module '@xsai/decide' {
105
+ interface DecisionModelProviderOptions {
106
+ decisions?: {
107
+ overrideInput?: OpenAIDecisionsInput;
108
+ };
109
+ }
110
+ }
111
+ declare const decisions: (options: HttpOptions) => DecisionModel;
112
+
113
+ declare module '@xsai/decide' {
114
+ interface DecisionModelProviderOptions {
115
+ systemone?: {
116
+ images?: readonly (string | {
117
+ base64: string;
118
+ content_type: 'image/jpeg' | 'image/png' | 'image/webp';
119
+ })[];
120
+ };
121
+ }
122
+ }
123
+ declare const systemone: (options: HttpOptions) => DecisionModel;
124
+
125
+ type ToDecisionModelOptions = Pick<LanguageModelOptions, 'maxOutputTokens' | 'providerOptions' | 'reasoningEffort' | 'temperature' | 'topP'>;
126
+ declare const toDecisionModel: (model: LanguageModel, options?: ToDecisionModelOptions) => DecisionModel;
127
+
128
+ export { DecisionRefusalError, decide, decisions, systemone, toDecisionModel };
129
+ export type { DecideResult, DecisionAnswer, DecisionAnswerFor, DecisionBooleanAnswer, DecisionChoice, DecisionChoiceAnswer, DecisionContent, DecisionModel, DecisionModelOptions, DecisionModelProviderOptions, DecisionModelResult, DecisionQuestion, DecisionQuestions, DecisionRefusal, DecisionScoreAnswer, DecisionScoreLevel, DecisionUsage, OpenAIDecisionsInput, ToDecisionModelOptions };
package/dist/index.js ADDED
@@ -0,0 +1,133 @@
1
+ import { XSAIError, sendRequest } from '@xsai/shared';
2
+ import { collect } from '@xsai/text';
3
+
4
+ class DecisionRefusalError extends XSAIError {
5
+ questionIds;
6
+ constructor(questionIds) {
7
+ super("decision-refusal", `Model refused questions: ${JSON.stringify(questionIds)}`);
8
+ this.questionIds = questionIds;
9
+ }
10
+ }
11
+ const decide = async (model, options) => {
12
+ const result = await model(options);
13
+ const refused = Object.keys(options.questions).filter((id) => result.answers[id]?.type === "refusal");
14
+ if (refused.length > 0)
15
+ throw new DecisionRefusalError(refused);
16
+ return result;
17
+ };
18
+
19
+ const toText = (content) => typeof content === "string" ? content : JSON.stringify(content);
20
+ const toDecisionUsage = (usage) => ({
21
+ inputTokens: usage.input_tokens ?? void 0,
22
+ outputTokens: usage.output_tokens ?? void 0,
23
+ totalTokens: usage.total_tokens ?? (usage.input_tokens != null && usage.output_tokens != null ? usage.input_tokens + usage.output_tokens : void 0)
24
+ });
25
+
26
+ const decisions = (options) => async (modelOptions) => {
27
+ const response = await sendRequest({
28
+ body: {
29
+ input: modelOptions.providerOptions?.decisions?.overrideInput ?? toText(modelOptions.input),
30
+ model: options.model,
31
+ questions: Object.entries(modelOptions.questions).map(([name, question]) => ({
32
+ choices: question.type === "choice" ? question.choices : void 0,
33
+ instructions: toText(question.instructions),
34
+ levels: question.type === "score" ? question.levels.map((level) => ({
35
+ description: level.description === void 0 ? void 0 : toText(level.description),
36
+ label: level.label
37
+ })) : void 0,
38
+ name,
39
+ type: question.type === "boolean" ? "predicate" : question.type
40
+ }))
41
+ },
42
+ path: "decisions",
43
+ signal: modelOptions.signal
44
+ }, options);
45
+ const json = await response.json();
46
+ return {
47
+ answers: Object.fromEntries(json.answers.flatMap((answer) => {
48
+ if (answer.type === "refusal")
49
+ return (answer.name === null ? Object.keys(modelOptions.questions) : [answer.name]).map((id) => [id, { type: "refusal" }]);
50
+ if (answer.type === "predicate")
51
+ return [[answer.name, { probability: answer.probability, type: "boolean" }]];
52
+ if (answer.type === "score") {
53
+ return [[answer.name, {
54
+ confidence: answer.confidence ?? void 0,
55
+ probabilities: Object.fromEntries(answer.probabilities.map((entry) => [entry.value, entry.probability])),
56
+ score: answer.score,
57
+ type: "score"
58
+ }]];
59
+ }
60
+ return [[answer.name, { choice: answer.choice, confidence: answer.confidence ?? void 0, probabilities: answer.probabilities, type: "choice" }]];
61
+ })),
62
+ usage: toDecisionUsage(json.usage)
63
+ };
64
+ };
65
+
66
+ const systemone = (options) => async (modelOptions) => {
67
+ const response = await sendRequest({
68
+ body: {
69
+ images: modelOptions.providerOptions?.systemone?.images,
70
+ model: options.model,
71
+ questions: Object.fromEntries(Object.entries(modelOptions.questions).map(([id, question]) => [id, {
72
+ criteria: question.type === "choice" ? Object.fromEntries(question.choices.map((choice) => [choice.value, choice.description ?? null])) : question.type === "score" ? question.levels.map((level) => level.description === void 0 ? level.label : `${level.label}: ${toText(level.description)}`) : void 0,
73
+ instructions: question.instructions,
74
+ type: question.type === "boolean" ? "noul" : question.type
75
+ }])),
76
+ state: modelOptions.input
77
+ },
78
+ path: "systemone",
79
+ signal: modelOptions.signal
80
+ }, options);
81
+ const json = await response.json();
82
+ return {
83
+ answers: Object.fromEntries(Object.entries(json.answers).map(([id, answer]) => {
84
+ if (answer.type === "noul")
85
+ return [id, { probability: answer.noul, type: "boolean" }];
86
+ if (answer.type === "choice") {
87
+ const question = modelOptions.questions[id];
88
+ return [id, {
89
+ choice: answer.choice,
90
+ confidence: answer.confidence,
91
+ probabilities: question.choices.map((choice) => ({ probability: answer.probabilities[choice.value], value: choice.value })),
92
+ type: "choice"
93
+ }];
94
+ }
95
+ return [id, { confidence: answer.confidence, probabilities: answer.probabilities, score: answer.score, type: "score" }];
96
+ })),
97
+ usage: toDecisionUsage(json.usage)
98
+ };
99
+ };
100
+
101
+ const toDecisionModel = (model, options = {}) => async (modelOptions) => {
102
+ const questions = Object.entries(modelOptions.questions);
103
+ const properties = Object.fromEntries(questions.map(([id, question]) => [id, question.type === "choice" ? { enum: question.choices.map((choice) => choice.value), type: "string" } : { maximum: question.type === "score" ? question.levels.length - 1 : 1, minimum: 0, type: "number" }]));
104
+ const result = await collect(await model({
105
+ ...options,
106
+ input: toText(modelOptions.input),
107
+ instructions: `Answer every question using the supplied input. For choice questions, return the selected value. For score questions, return a numeric rating from 0 to levels.length - 1, allowing fractions. For boolean questions, estimate P(true) between 0 and 1. Return only the JSON object required by the output schema.
108
+ Questions:
109
+ ${JSON.stringify(modelOptions.questions)}`,
110
+ outputFormat: { additionalProperties: false, properties, required: questions.map(([id]) => id), type: "object" },
111
+ signal: modelOptions.signal
112
+ }));
113
+ if (result.reason === "refusal" || typeof result.message.content !== "string" && result.message.content.some((part) => part.type === "refusal"))
114
+ throw new DecisionRefusalError(questions.map(([id]) => id));
115
+ if (result.status !== "completed" || result.toolCalls.length > 0)
116
+ throw new XSAIError("invalid-response", "LanguageModel did not complete a structured decision output");
117
+ const output = JSON.parse(result.text);
118
+ const invalid = questions.filter(([id, question]) => {
119
+ const value = output[id];
120
+ if (question.type === "choice")
121
+ return !question.choices.some((choice) => choice.value === value);
122
+ const max = question.type === "score" ? question.levels.length - 1 : 1;
123
+ return typeof value !== "number" || value < 0 || value > max;
124
+ });
125
+ if (invalid.length > 0)
126
+ throw new XSAIError("invalid-response", `LanguageModel returned out-of-range answers: ${JSON.stringify(invalid.map(([id]) => id))}`);
127
+ return {
128
+ answers: Object.fromEntries(questions.map(([id, question]) => [id, question.type === "choice" ? { choice: output[id], type: "choice" } : question.type === "score" ? { score: output[id], type: "score" } : { probability: output[id], type: "boolean" }])),
129
+ usage: result.usage ?? {}
130
+ };
131
+ };
132
+
133
+ export { DecisionRefusalError, decide, decisions, systemone, toDecisionModel };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@xsai/decide",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "1.0.0-beta.1",
5
+ "description": "extra-small AI SDK: classify input by answering yes/no questions with probabilities.",
6
+ "author": "Moeru AI",
7
+ "license": "MIT",
8
+ "homepage": "https://xsai.js.org",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/moeru-ai/xsai.git",
12
+ "directory": "packages/decide"
13
+ },
14
+ "bugs": "https://github.com/moeru-ai/xsai/issues",
15
+ "keywords": [
16
+ "xsai",
17
+ "ai",
18
+ "openai",
19
+ "decide",
20
+ "classification",
21
+ "logprobs"
22
+ ],
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./package.json": "./package.json"
30
+ },
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "dependencies": {
35
+ "@xsai/shared": "1.0.0-beta.1",
36
+ "@xsai/text": "1.0.0-beta.1"
37
+ },
38
+ "scripts": {
39
+ "build": "pkgroll --clean-dist",
40
+ "test": "vitest run --exclude e2e/**",
41
+ "test:watch": "vitest"
42
+ },
43
+ "main": "./dist/index.js",
44
+ "types": "./dist/index.d.ts"
6
45
  }