@opencode/ai 0.0.0-dev-21797 → 0.0.0-dev-21799

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 (52) hide show
  1. package/README.md +55 -55
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/decision-client.d.ts +21 -0
  5. package/dist/decision-client.js +55 -0
  6. package/dist/decision.d.ts +452 -0
  7. package/dist/decision.js +143 -0
  8. package/dist/experimental.d.ts +0 -3
  9. package/dist/experimental.js +0 -2
  10. package/dist/index.d.ts +5 -0
  11. package/dist/index.js +4 -0
  12. package/dist/promise.d.ts +10 -1
  13. package/dist/promise.js +5 -0
  14. package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
  15. package/dist/protocols/cloudflare-run-decisions.js +36 -0
  16. package/dist/protocols/index.d.ts +3 -0
  17. package/dist/protocols/index.js +3 -0
  18. package/dist/protocols/openai-decisions.d.ts +22 -0
  19. package/dist/protocols/openai-decisions.js +108 -0
  20. package/dist/protocols/system-one.d.ts +99 -0
  21. package/dist/protocols/system-one.js +228 -0
  22. package/dist/providers/baseten.d.ts +4 -10
  23. package/dist/providers/baseten.js +21 -8
  24. package/dist/providers/cloudflare-ai-gateway.d.ts +1 -3
  25. package/dist/providers/cloudflare-ai-gateway.js +10 -10
  26. package/dist/providers/cloudflare-workers-ai.d.ts +1 -3
  27. package/dist/providers/cloudflare-workers-ai.js +11 -12
  28. package/dist/providers/digitalocean.d.ts +3 -9
  29. package/dist/providers/digitalocean.js +10 -10
  30. package/dist/providers/openai.d.ts +5 -10
  31. package/dist/providers/openai.js +11 -7
  32. package/dist/providers/opencode.d.ts +3 -9
  33. package/dist/providers/opencode.js +9 -9
  34. package/dist/providers/openrouter.d.ts +4 -10
  35. package/dist/providers/openrouter.js +8 -9
  36. package/dist/providers/typesafe-ai.d.ts +3 -9
  37. package/dist/providers/typesafe-ai.js +9 -9
  38. package/dist/providers/vercel-ai-gateway.d.ts +4 -15
  39. package/dist/providers/vercel-ai-gateway.js +13 -80
  40. package/dist/route/decision.d.ts +57 -0
  41. package/dist/route/decision.js +74 -0
  42. package/package.json +3 -3
  43. package/dist/experimental/cloudflare-run-evaluation.d.ts +0 -15
  44. package/dist/experimental/cloudflare-run-evaluation.js +0 -43
  45. package/dist/experimental/evaluation-client.d.ts +0 -21
  46. package/dist/experimental/evaluation-client.js +0 -64
  47. package/dist/experimental/evaluation.d.ts +0 -242
  48. package/dist/experimental/evaluation.js +0 -108
  49. package/dist/experimental/openai-decisions.d.ts +0 -23
  50. package/dist/experimental/openai-decisions.js +0 -115
  51. package/dist/experimental/system-one.d.ts +0 -114
  52. package/dist/experimental/system-one.js +0 -140
package/dist/promise.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Effect, Layer } from "effect";
2
2
  import { AIClient } from "./ai-client.js";
3
+ import { type DecisionModel, type DecisionQuestions, type DecisionRequestInput } from "./decision.js";
3
4
  import type { AwaitOptions, Event, Snapshot } from "./generation.js";
4
5
  import { type ImageModel, type ImageRequest, type ImageRequestInput } from "./image.js";
5
6
  import { LLM } from "./index.js";
@@ -12,7 +13,7 @@ import { type TranscriptionModel, type TranscriptionRequest, type TranscriptionR
12
13
  import { type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js";
13
14
  /**
14
15
  * Promise-first entrypoint for scripts and non-Effect callers. One `ManagedRuntime` hosts the LLM, image, video, speech,
15
- * and transcription clients over a request executor; every method runs the corresponding Effect API and rethrows
16
+ * transcription and decision clients over a request executor; every method runs the corresponding Effect API and rethrows
16
17
  * `AIError` unchanged. `file` and `write` load `node:fs/promises` on first use, so importing this module does not.
17
18
  */
18
19
  export interface Options {
@@ -525,6 +526,10 @@ export declare const make: (options?: Options) => {
525
526
  start: <const Model extends TranscriptionModel>(input: TranscriptionRequestInput<Model> | TranscriptionRequest, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
526
527
  resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
527
528
  };
529
+ decision: {
530
+ request: typeof import("./decision.js").request;
531
+ generate: <const Model extends DecisionModel, const Questions extends DecisionQuestions>(input: DecisionRequestInput<Model, Questions>, options?: RunOptions) => Promise<import("./decision.js").DecisionResponseFor<Questions>>;
532
+ };
528
533
  dispose: () => Promise<void>;
529
534
  };
530
535
  export type Client = ReturnType<typeof make>;
@@ -1016,6 +1021,10 @@ export declare const ai: {
1016
1021
  start: <const Model extends TranscriptionModel>(input: TranscriptionRequestInput<Model> | TranscriptionRequest, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
1017
1022
  resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
1018
1023
  };
1024
+ decision: {
1025
+ request: typeof import("./decision.js").request;
1026
+ generate: <const Model extends DecisionModel, const Questions extends DecisionQuestions>(input: DecisionRequestInput<Model, Questions>, options?: RunOptions) => Promise<import("./decision.js").DecisionResponseFor<Questions>>;
1027
+ };
1019
1028
  dispose: () => Promise<void>;
1020
1029
  };
1021
1030
  export * as AI from "./promise.js";
package/dist/promise.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Effect, Layer, ManagedRuntime, Stream } from "effect";
2
2
  import { AIClient } from "./ai-client.js";
3
+ import { Decision } from "./decision.js";
3
4
  import { Image } from "./image.js";
4
5
  import { LLM } from "./index.js";
5
6
  import { Media } from "./media.js";
@@ -92,6 +93,10 @@ export const make = (options = {}) => {
92
93
  start: (input, options) => run(Transcription.start(input), options).then(handle),
93
94
  resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle),
94
95
  },
96
+ decision: {
97
+ request: Decision.request,
98
+ generate: (input, options) => run(Decision.generate(input), options),
99
+ },
95
100
  dispose: () => runtime.dispose(),
96
101
  };
97
102
  };
@@ -0,0 +1,9 @@
1
+ import { DecisionRoute } from "../route/decision.js";
2
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One body as `input`; media defaults to Clef's top-level lists. */
3
+ export declare const protocol: DecisionRoute.Protocol;
4
+ /** Providers set the Run API base, `.../client/v4/accounts/{account}/ai/run`, with `route.with(...)`. */
5
+ export declare const route: DecisionRoute.Route;
6
+ export declare const CloudflareRunDecisions: {
7
+ readonly protocol: DecisionRoute.Protocol;
8
+ readonly route: DecisionRoute.Route;
9
+ };
@@ -0,0 +1,36 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionRoute } from "../route/decision.js";
3
+ import { Endpoint } from "../route/endpoint.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { SystemOne } from "./system-one.js";
6
+ const ID = "cloudflare-run-decisions";
7
+ const NAME = "Cloudflare Run";
8
+ // Workers AI models answer with the System One response; third-party models such as TypeSafe Jev wrap it in a
9
+ // completed run record.
10
+ const Envelope = Schema.Struct({
11
+ result: Schema.Union([
12
+ SystemOne.Response,
13
+ Schema.Struct({ state: Schema.Literal("Completed"), result: SystemOne.Response }),
14
+ ]),
15
+ });
16
+ const decodeEnvelope = MediaProtocol.identity({ id: ID, name: NAME, provider: "cloudflare-workers-ai" }).decodeJson(Envelope);
17
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One body as `input`; media defaults to Clef's top-level lists. */
18
+ export const protocol = DecisionRoute.protocol({
19
+ id: ID,
20
+ name: NAME,
21
+ inlineMedia: true,
22
+ body: {
23
+ from: (request) => SystemOne.encodeBody(request, "images").pipe(Effect.map((input) => ({ model: request.model.id, input }))),
24
+ },
25
+ response: {
26
+ decode: (response, context) => decodeEnvelope(response).pipe(Effect.flatMap((output) => SystemOne.toResponse("answers" in output.value.result ? output.value.result : output.value.result.result, context.request, context.providerMetadataKey, output.invalid))),
27
+ },
28
+ });
29
+ /** Providers set the Run API base, `.../client/v4/accounts/{account}/ai/run`, with `route.with(...)`. */
30
+ export const route = DecisionRoute.make({
31
+ id: ID,
32
+ provider: "cloudflare-workers-ai",
33
+ protocol,
34
+ endpoint: Endpoint.path(""),
35
+ });
36
+ export const CloudflareRunDecisions = { protocol, route };
@@ -1,14 +1,17 @@
1
1
  export * as AnthropicMessages from "./anthropic-messages.js";
2
2
  export * as BedrockConverse from "./bedrock-converse.js";
3
+ export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js";
3
4
  export * as CohereChat from "./cohere-chat.js";
4
5
  export * as Gemini from "./gemini.js";
5
6
  export * as GoogleInteractions from "./google-interactions.js";
6
7
  export * as MistralChat from "./mistral-chat.js";
7
8
  export * as OpenAIChat from "./openai-chat.js";
9
+ export * as OpenAIDecisions from "./openai-decisions.js";
8
10
  export * as OpenAIImages from "./openai-images.js";
9
11
  export * as OpenAICompatibleChat from "./openai-compatible-chat.js";
10
12
  export * as OpenAICompatibleResponses from "./openai-compatible-responses.js";
11
13
  export * as OpenAIResponses from "./openai-responses.js";
12
14
  export * as OpenResponses from "./open-responses.js";
13
15
  export * as OpenResponsesChannel from "./open-responses-channel.js";
16
+ export * as SystemOne from "./system-one.js";
14
17
  export * as XAIResponses from "./xai-responses.js";
@@ -1,14 +1,17 @@
1
1
  export * as AnthropicMessages from "./anthropic-messages.js";
2
2
  export * as BedrockConverse from "./bedrock-converse.js";
3
+ export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js";
3
4
  export * as CohereChat from "./cohere-chat.js";
4
5
  export * as Gemini from "./gemini.js";
5
6
  export * as GoogleInteractions from "./google-interactions.js";
6
7
  export * as MistralChat from "./mistral-chat.js";
7
8
  export * as OpenAIChat from "./openai-chat.js";
9
+ export * as OpenAIDecisions from "./openai-decisions.js";
8
10
  export * as OpenAIImages from "./openai-images.js";
9
11
  export * as OpenAICompatibleChat from "./openai-compatible-chat.js";
10
12
  export * as OpenAICompatibleResponses from "./openai-compatible-responses.js";
11
13
  export * as OpenAIResponses from "./openai-responses.js";
12
14
  export * as OpenResponses from "./open-responses.js";
13
15
  export * as OpenResponsesChannel from "./open-responses-channel.js";
16
+ export * as SystemOne from "./system-one.js";
14
17
  export * as XAIResponses from "./xai-responses.js";
@@ -0,0 +1,22 @@
1
+ import { Schema } from "effect";
2
+ import { DecisionRoute } from "../route/decision.js";
3
+ import { type ProviderOptions } from "../schema/index.js";
4
+ export declare const DEFAULT_BASE_URL = "https://api.openai.com/v1";
5
+ export declare const PATH = "/decisions";
6
+ declare const Options: Schema.Struct<{
7
+ readonly promptCacheKey: Schema.optional<Schema.String>;
8
+ readonly promptCacheOptions: Schema.optional<Schema.Struct<{
9
+ readonly mode: Schema.optional<Schema.String>;
10
+ readonly ttl: Schema.optional<Schema.String>;
11
+ }>>;
12
+ readonly safetyIdentifier: Schema.optional<Schema.String>;
13
+ }>;
14
+ /** Known fields map to their wire names; anything else is sent as given. */
15
+ export type OptionsInput = ProviderOptions & typeof Options.Encoded;
16
+ export declare const protocol: DecisionRoute.Protocol;
17
+ export declare const route: DecisionRoute.Route;
18
+ export declare const OpenAIDecisions: {
19
+ readonly protocol: DecisionRoute.Protocol;
20
+ readonly route: DecisionRoute.Route;
21
+ };
22
+ export {};
@@ -0,0 +1,108 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js";
7
+ import { encodeJson } from "../utils/json.js";
8
+ import { OpenResponses } from "./open-responses.js";
9
+ import { ProviderShared } from "./shared.js";
10
+ const ID = "openai-decisions";
11
+ const NAME = "OpenAI Decisions";
12
+ export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
13
+ export const PATH = "/decisions";
14
+ const Options = Schema.Struct({
15
+ promptCacheKey: Schema.optional(Schema.String),
16
+ promptCacheOptions: Schema.optional(Schema.Struct({ mode: Schema.optional(Schema.String), ttl: Schema.optional(Schema.String) })),
17
+ safetyIdentifier: Schema.optional(Schema.String),
18
+ });
19
+ const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }));
20
+ const ChoiceValue = Schema.Union([Schema.String, Schema.Boolean]);
21
+ const Answer = Schema.Union([
22
+ Schema.Struct({ type: Schema.Literal("predicate"), name: Schema.String, probability: Probability }),
23
+ Schema.Struct({
24
+ type: Schema.Literal("choice"),
25
+ name: Schema.String,
26
+ choice: ChoiceValue,
27
+ probabilities: Schema.Array(Schema.Struct({ value: ChoiceValue, probability: Probability })),
28
+ confidence: Probability,
29
+ }),
30
+ Schema.Struct({
31
+ type: Schema.Literal("score"),
32
+ name: Schema.String,
33
+ score: Schema.Number,
34
+ probabilities: Schema.Array(Schema.Struct({ value: Schema.Int, label: Schema.String, probability: Probability })),
35
+ confidence: Probability,
36
+ }),
37
+ Schema.Struct({ type: Schema.Literal("refusal"), name: Schema.String }),
38
+ ]);
39
+ const Response = Schema.Struct({
40
+ model: Schema.String,
41
+ answers: Schema.Array(Answer),
42
+ usage: Schema.optional(OpenResponses.OpenResponsesUsage),
43
+ });
44
+ const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options));
45
+ const fromRequest = Effect.fn("OpenAIDecisions.fromRequest")(function* (request) {
46
+ const options = yield* decodeOptions(request.providerOptions ?? {});
47
+ const { promptCacheKey: _, promptCacheOptions: __, safetyIdentifier: ___, ...native } = request.providerOptions ?? {};
48
+ return {
49
+ ...mergeJsonRecords({
50
+ prompt_cache_key: options.promptCacheKey,
51
+ prompt_cache_options: options.promptCacheOptions,
52
+ safety_identifier: options.safetyIdentifier,
53
+ ...native,
54
+ }, request.http?.body),
55
+ model: request.model.id,
56
+ input: [{ role: "user", content: yield* Effect.forEach(request.input, (part) => inputPart(request, part)) }],
57
+ questions: request.questions,
58
+ };
59
+ });
60
+ // `input_json` takes an object or a list of objects; other JSON values go as text.
61
+ const inputPart = (request, part) => {
62
+ if (part.type === "text")
63
+ return Effect.succeed({ type: "input_text", text: part.text });
64
+ if (part.type === "json")
65
+ return Effect.succeed(isObject(part.value) || (Array.isArray(part.value) && part.value.every(isObject))
66
+ ? { type: "input_json", data: part.value }
67
+ : { type: "input_text", text: encodeJson(part.value) });
68
+ if (part.media.kind !== "image")
69
+ return Effect.fail(new AIError({
70
+ reason: new UnsupportedOperationError({
71
+ operation: "decision.media",
72
+ provider: request.model.provider,
73
+ route: request.model.route.id,
74
+ message: `${NAME} takes images only; got ${part.media.kind} media`,
75
+ }),
76
+ }));
77
+ return ProviderShared.mediaReference(part.media, undefined, `${NAME} image input`).pipe(Effect.map((reference) => ({ type: "input_image", image_url: reference.value })));
78
+ };
79
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
80
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "openai" }).decodeJson(Response);
81
+ export const protocol = DecisionRoute.protocol({
82
+ id: ID,
83
+ name: NAME,
84
+ body: { from: fromRequest },
85
+ response: {
86
+ decode: Effect.fn("OpenAIDecisions.decodeResponse")(function* (response, context) {
87
+ const output = yield* decodeDocument(response);
88
+ const answers = output.value.answers.map((answer) => answer.type === "refusal" ? { name: answer.name, type: "error", reason: "refusal" } : answer);
89
+ const byName = new Map(answers.map((answer) => [answer.name, answer]));
90
+ const ordered = context.request.questions.flatMap((question) => byName.get(question.name) ?? []);
91
+ return new DecisionResponse({
92
+ answers: ordered.length === answers.length ? ordered : answers,
93
+ usage: OpenResponses.mapUsage(output.value.usage, context.providerMetadataKey),
94
+ providerMetadata: { [context.providerMetadataKey]: { model: output.value.model } },
95
+ });
96
+ }),
97
+ },
98
+ });
99
+ export const route = DecisionRoute.make({
100
+ id: ID,
101
+ provider: "openai",
102
+ protocol,
103
+ endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),
104
+ });
105
+ export const OpenAIDecisions = {
106
+ protocol,
107
+ route,
108
+ };
@@ -0,0 +1,99 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, type DecisionModelCompatibility, type DecisionRequestFor } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { AIError } from "../schema/index.js";
5
+ export declare const DEFAULT_PATH = "/systemone";
6
+ export declare const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
7
+ /** `messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
8
+ type ImageInput = NonNullable<DecisionModelCompatibility["imageInput"]> | "messages";
9
+ export declare const Response: Schema.Struct<{
10
+ readonly model: Schema.String;
11
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
12
+ readonly type: Schema.Literal<"noul">;
13
+ readonly noul: Schema.Number;
14
+ }>, Schema.Struct<{
15
+ readonly type: Schema.Literal<"choice">;
16
+ readonly choice: Schema.String;
17
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
18
+ readonly confidence: Schema.Number;
19
+ }>, Schema.Struct<{
20
+ readonly type: Schema.Literal<"score">;
21
+ readonly score: Schema.Number;
22
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
23
+ readonly confidence: Schema.Number;
24
+ }>]>>;
25
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
26
+ readonly input_tokens: Schema.optional<Schema.Number>;
27
+ readonly output_tokens: Schema.optional<Schema.Number>;
28
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
29
+ readonly id: Schema.optional<Schema.String>;
30
+ readonly provider: Schema.optional<Schema.String>;
31
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
32
+ }>;
33
+ export type Response = Schema.Schema.Type<typeof Response>;
34
+ /** The System One body without `model`; media goes where the model's `imageInput` says, else `fallback`. */
35
+ export declare const encodeBody: (request: DecisionRequestFor, fallback: ImageInput) => Effect.Effect<{
36
+ questions: any;
37
+ state: unknown;
38
+ assets?: undefined;
39
+ } | {
40
+ questions: any;
41
+ state: readonly unknown[];
42
+ assets: {
43
+ [k: string]: {
44
+ type: string;
45
+ format: string;
46
+ data_base64: string;
47
+ };
48
+ };
49
+ }, AIError, never>;
50
+ /** Map System One's answers, keyed by question name, back to the request's question order. */
51
+ export declare const toResponse: (data: Response, request: DecisionRequestFor, providerMetadataKey: string, invalid: (message: string) => AIError) => Effect.Effect<never, AIError, never> | Effect.Effect<DecisionResponse, never, never>;
52
+ export declare const protocol: DecisionRoute.Protocol;
53
+ /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
54
+ export declare const route: DecisionRoute.Route;
55
+ export declare const SystemOne: {
56
+ readonly Response: Schema.Struct<{
57
+ readonly model: Schema.String;
58
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
59
+ readonly type: Schema.Literal<"noul">;
60
+ readonly noul: Schema.Number;
61
+ }>, Schema.Struct<{
62
+ readonly type: Schema.Literal<"choice">;
63
+ readonly choice: Schema.String;
64
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
65
+ readonly confidence: Schema.Number;
66
+ }>, Schema.Struct<{
67
+ readonly type: Schema.Literal<"score">;
68
+ readonly score: Schema.Number;
69
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
70
+ readonly confidence: Schema.Number;
71
+ }>]>>;
72
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
73
+ readonly input_tokens: Schema.optional<Schema.Number>;
74
+ readonly output_tokens: Schema.optional<Schema.Number>;
75
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
76
+ readonly id: Schema.optional<Schema.String>;
77
+ readonly provider: Schema.optional<Schema.String>;
78
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
79
+ }>;
80
+ readonly encodeBody: (request: DecisionRequestFor, fallback: ImageInput) => Effect.Effect<{
81
+ questions: any;
82
+ state: unknown;
83
+ assets?: undefined;
84
+ } | {
85
+ questions: any;
86
+ state: readonly unknown[];
87
+ assets: {
88
+ [k: string]: {
89
+ type: string;
90
+ format: string;
91
+ data_base64: string;
92
+ };
93
+ };
94
+ }, AIError, never>;
95
+ readonly toResponse: typeof toResponse;
96
+ readonly protocol: DecisionRoute.Protocol;
97
+ readonly route: DecisionRoute.Route;
98
+ };
99
+ export {};
@@ -0,0 +1,228 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { DecisionResponse, } from "../decision.js";
3
+ import { DecisionRoute } from "../route/decision.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { AIError, UnsupportedOperationError, Usage, mergeJsonRecords } from "../schema/index.js";
7
+ import { encodeJson } from "../utils/json.js";
8
+ import { JsonObject, ProviderShared } from "./shared.js";
9
+ export const DEFAULT_PATH = "/systemone";
10
+ export const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1";
11
+ const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }));
12
+ const Answer = Schema.Union([
13
+ Schema.Struct({ type: Schema.Literal("noul"), noul: Probability }),
14
+ Schema.Struct({
15
+ type: Schema.Literal("choice"),
16
+ choice: Schema.String,
17
+ probabilities: Schema.Record(Schema.String, Probability),
18
+ confidence: Probability,
19
+ }),
20
+ Schema.Struct({
21
+ type: Schema.Literal("score"),
22
+ score: Schema.Number,
23
+ probabilities: Schema.Record(Schema.String, Probability),
24
+ confidence: Probability,
25
+ }),
26
+ ]).pipe(Schema.toTaggedUnion("type"));
27
+ const NativeUsage = Schema.StructWithRest(Schema.Struct({
28
+ input_tokens: Schema.optional(Schema.Number),
29
+ output_tokens: Schema.optional(Schema.Number),
30
+ }), [JsonObject]);
31
+ export const Response = Schema.Struct({
32
+ model: Schema.String,
33
+ answers: Schema.Record(Schema.String, Answer),
34
+ usage: Schema.optional(NativeUsage),
35
+ id: Schema.optional(Schema.String),
36
+ provider: Schema.optional(Schema.String),
37
+ provider_metadata: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown))),
38
+ });
39
+ const ID = "system-one";
40
+ const NAME = "System One";
41
+ /** The System One body without `model`; media goes where the model's `imageInput` says, else `fallback`. */
42
+ export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (request, fallback) {
43
+ const questions = yield* encodeQuestions(request.questions);
44
+ const placed = yield* placeMedia(request, request.model.compatibility?.imageInput ?? fallback);
45
+ return { ...mergeJsonRecords(request.providerOptions, request.http?.body), ...placed, questions };
46
+ });
47
+ const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
48
+ if (question.type === "predicate")
49
+ return Effect.succeed([question.name, { type: "noul", instructions: question.instructions }]);
50
+ if (question.type === "score")
51
+ return Effect.succeed([
52
+ question.name,
53
+ {
54
+ type: "score",
55
+ instructions: question.instructions,
56
+ criteria: question.levels.map((level) => level.description === undefined ? level.label : `${level.label}: ${level.description}`),
57
+ },
58
+ ]);
59
+ // Options are map keys, so `true` is sent as "true" and mapped back by `choiceValue`.
60
+ const keys = question.choices.map((choice) => String(choice.value));
61
+ if (new Set(keys).size !== keys.length)
62
+ return Effect.fail(ProviderShared.invalidRequest(`System One choice options are strings; "${question.name}" has a boolean and a string with the same text`));
63
+ return Effect.succeed([
64
+ question.name,
65
+ {
66
+ type: "choice",
67
+ instructions: question.instructions,
68
+ criteria: Object.fromEntries(question.choices.map((choice) => [String(choice.value), choice.description ?? null])),
69
+ },
70
+ ]);
71
+ }).pipe(Effect.map(Object.fromEntries));
72
+ const placeMedia = Effect.fnUntraced(function* (request, imageInput) {
73
+ const parts = request.input;
74
+ const unsupported = (asset, accepted) => new AIError({
75
+ reason: new UnsupportedOperationError({
76
+ operation: "decision.media",
77
+ provider: request.model.provider,
78
+ route: request.model.route.id,
79
+ message: `${NAME} takes ${accepted} here; got ${asset.mediaType}`,
80
+ }),
81
+ });
82
+ const media = parts.flatMap((part) => (part.type === "media" ? [part.media] : []));
83
+ if (media.length === 0)
84
+ return { state: state(parts.map(plain)) };
85
+ if (imageInput === "state")
86
+ return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) };
87
+ // Chat-style content in one user message: text and JSON as text parts, media as in `state`.
88
+ if (imageInput === "messages")
89
+ return {
90
+ state: {
91
+ messages: [
92
+ {
93
+ role: "user",
94
+ content: yield* Effect.forEach(parts, (part) => part.type === "media"
95
+ ? stateItem(part, unsupported)
96
+ : Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) })),
97
+ },
98
+ ],
99
+ },
100
+ };
101
+ if (imageInput === "images") {
102
+ const lists = { image: "images", audio: "audio", video: "videos" };
103
+ const unplaced = media.find((asset) => !Object.hasOwn(lists, asset.kind));
104
+ if (unplaced !== undefined)
105
+ return yield* unsupported(unplaced, "images, audio and video");
106
+ const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
107
+ const fields = Object.fromEntries(Object.entries(lists).flatMap(([kind, field]) => {
108
+ const items = inline.filter((_, index) => media[index].kind === kind).map((item) => item.dataUrl);
109
+ return items.length === 0 ? [] : [[field, items]];
110
+ }));
111
+ return { state: state(parts.filter((part) => part.type !== "media").map(plain)), ...fields };
112
+ }
113
+ const unplaced = media.find((asset) => asset.kind !== "image");
114
+ if (unplaced !== undefined)
115
+ return yield* unsupported(unplaced, "images");
116
+ const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
117
+ // Every occurrence of a reference string in the body is replaced with its image, so it must not be ordinary text.
118
+ const reference = (index) => `<image-${index + 1}>`;
119
+ const items = parts.reduce((acc, part) => part.type === "media"
120
+ ? { next: acc.next + 1, values: [...acc.values, reference(acc.next)] }
121
+ : { next: acc.next, values: [...acc.values, plain(part)] }, { next: 0, values: [] }).values;
122
+ return {
123
+ state: items,
124
+ assets: Object.fromEntries(inline.map((item, index) => [
125
+ reference(index),
126
+ { type: "image", format: item.mime.slice("image/".length), data_base64: item.base64 },
127
+ ])),
128
+ };
129
+ });
130
+ /** A lone text or JSON part is the state itself; several are a list. */
131
+ const state = (items) => (items.length === 1 ? items[0] : items);
132
+ const plain = (part) => {
133
+ if (part.type === "text")
134
+ return part.text;
135
+ if (part.type === "json")
136
+ return part.value;
137
+ return undefined;
138
+ };
139
+ const stateItem = (part, unsupported) => {
140
+ if (part.type !== "media")
141
+ return Effect.succeed(plain(part));
142
+ const asset = part.media;
143
+ if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
144
+ return Effect.fail(unsupported(asset, "images, audio and video"));
145
+ return ProviderShared.requireInlineMedia(NAME, asset).pipe(Effect.map((inline) => {
146
+ if (asset.kind === "image")
147
+ return { type: "image_url", image_url: { url: inline.dataUrl } };
148
+ if (asset.kind === "video")
149
+ return { type: "video_url", video_url: { url: inline.dataUrl } };
150
+ return { type: "input_audio", input_audio: { data: inline.base64, format: inline.mime.slice("audio/".length) } };
151
+ }));
152
+ };
153
+ /** Map System One's answers, keyed by question name, back to the request's question order. */
154
+ export const toResponse = (data, request, providerMetadataKey, invalid) => {
155
+ const names = request.questions.map((question) => question.name);
156
+ if (Object.keys(data.answers).length !== names.length || !names.every((name) => Object.hasOwn(data.answers, name)))
157
+ return Effect.fail(invalid("System One answers do not match the requested questions"));
158
+ return Effect.succeed(new DecisionResponse({
159
+ answers: request.questions.map((question) => toAnswer(question, data.answers[question.name])),
160
+ usage: data.usage === undefined
161
+ ? undefined
162
+ : new Usage({
163
+ inputTokens: data.usage.input_tokens,
164
+ outputTokens: data.usage.output_tokens,
165
+ totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
166
+ providerMetadata: { [providerMetadataKey]: data.usage },
167
+ }),
168
+ providerMetadata: {
169
+ [providerMetadataKey]: {
170
+ model: data.model,
171
+ ...(data.id === undefined ? {} : { responseId: data.id }),
172
+ ...(data.provider === undefined ? {} : { provider: data.provider }),
173
+ ...data.provider_metadata?.[providerMetadataKey],
174
+ },
175
+ },
176
+ }));
177
+ };
178
+ const toAnswer = (question, answer) => {
179
+ if (answer.type === "noul")
180
+ return { name: question.name, type: "predicate", probability: answer.noul };
181
+ if (answer.type === "choice") {
182
+ const choices = question.type === "choice" ? question.choices : [];
183
+ const value = (key) => choices.find((choice) => String(choice.value) === key)?.value ?? key;
184
+ const rank = (key) => {
185
+ const index = choices.findIndex((choice) => String(choice.value) === key);
186
+ return index === -1 ? choices.length : index;
187
+ };
188
+ return {
189
+ name: question.name,
190
+ type: "choice",
191
+ choice: value(answer.choice),
192
+ probabilities: Object.entries(answer.probabilities)
193
+ .toSorted(([a], [b]) => rank(a) - rank(b))
194
+ .map(([key, probability]) => ({ value: value(key), probability })),
195
+ confidence: answer.confidence,
196
+ };
197
+ }
198
+ const levels = question.type === "score" ? question.levels : [];
199
+ return {
200
+ name: question.name,
201
+ type: "score",
202
+ score: answer.score,
203
+ probabilities: Object.entries(answer.probabilities)
204
+ .map(([key, probability]) => ({ value: Number(key), label: levels[Number(key)]?.label ?? key, probability }))
205
+ .toSorted((a, b) => a.value - b.value),
206
+ confidence: answer.confidence,
207
+ };
208
+ };
209
+ const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "typesafe-ai" }).decodeJson(Response);
210
+ export const protocol = DecisionRoute.protocol({
211
+ id: ID,
212
+ name: NAME,
213
+ inlineMedia: true,
214
+ body: {
215
+ from: (request) => encodeBody(request, "assets").pipe(Effect.map((body) => ({ ...body, model: request.model.id }))),
216
+ },
217
+ response: {
218
+ decode: (response, context) => decodeDocument(response).pipe(Effect.flatMap((output) => toResponse(output.value, context.request, context.providerMetadataKey, output.invalid))),
219
+ },
220
+ });
221
+ /** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
222
+ export const route = DecisionRoute.make({
223
+ id: ID,
224
+ provider: "typesafe-ai",
225
+ protocol,
226
+ endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }),
227
+ });
228
+ export const SystemOne = { Response, encodeBody, toResponse, protocol, route };
@@ -8,7 +8,7 @@ export type LanguageModelOptions = Omit<RouteDefaultsInput, "providerOptions"> &
8
8
  readonly baseURL?: string;
9
9
  readonly providerOptions?: OpenAIProviderOptionsInput;
10
10
  };
11
- export interface BasetenEvaluationOptions {
11
+ export interface BasetenDecisionOptions {
12
12
  readonly [key: string]: unknown;
13
13
  readonly max_len?: number;
14
14
  }
@@ -283,21 +283,15 @@ export declare const routes: Route<{
283
283
  export declare const configure: (input?: LanguageModelOptions) => {
284
284
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
285
285
  model: (modelID: string | ModelID) => import("../schema/options.js").LanguageModel<import("./openai-options.js").OpenAIOptionsInput, import("../route/client.js").CompactionOperations | undefined>;
286
- experimental: {
287
- evaluation: (modelID: string | ModelID) => import("../experimental.js").EvaluationModel<BasetenEvaluationOptions>;
288
- };
286
+ decision: (modelID: string | ModelID) => import("../decision.js").DecisionModel<BasetenDecisionOptions>;
289
287
  configure: typeof configure;
290
288
  };
291
289
  export declare const provider: {
292
290
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
293
291
  model: (modelID: string | ModelID) => import("../schema/options.js").LanguageModel<import("./openai-options.js").OpenAIOptionsInput, import("../route/client.js").CompactionOperations | undefined>;
294
- experimental: {
295
- evaluation: (modelID: string | ModelID) => import("../experimental.js").EvaluationModel<BasetenEvaluationOptions>;
296
- };
292
+ decision: (modelID: string | ModelID) => import("../decision.js").DecisionModel<BasetenDecisionOptions>;
297
293
  configure: typeof configure;
298
294
  };
299
- export declare const experimental: {
300
- evaluation: (modelID: string | ModelID) => import("../experimental.js").EvaluationModel<BasetenEvaluationOptions>;
301
- };
295
+ export declare const decision: (modelID: string | ModelID) => import("../decision.js").DecisionModel<BasetenDecisionOptions>;
302
296
  export declare const model: ProviderPackage.Definition<Settings, OpenAIProviderOptionsInput>["model"];
303
297
  export * as Baseten from "./baseten.js";