@opencode/ai 0.0.0-dev-21713 → 0.0.0-dev-21730

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 (31) hide show
  1. package/README.md +29 -2
  2. package/dist/experimental/cloudflare-run-evaluation.d.ts +15 -0
  3. package/dist/experimental/cloudflare-run-evaluation.js +43 -0
  4. package/dist/experimental/system-one.d.ts +100 -2
  5. package/dist/experimental/system-one.js +62 -57
  6. package/dist/protocols/alibaba-images.d.ts +19 -0
  7. package/dist/protocols/alibaba-images.js +76 -0
  8. package/dist/protocols/cloudflare-workers-ai-images.d.ts +17 -0
  9. package/dist/protocols/cloudflare-workers-ai-images.js +72 -0
  10. package/dist/protocols/openai-images.d.ts +15 -5
  11. package/dist/protocols/openai-images.js +23 -23
  12. package/dist/provider-error.js +3 -1
  13. package/dist/providers/alibaba.d.ts +2 -0
  14. package/dist/providers/alibaba.js +5 -1
  15. package/dist/providers/baseten.d.ts +13 -0
  16. package/dist/providers/baseten.js +15 -2
  17. package/dist/providers/cloudflare-ai-gateway.d.ts +5 -0
  18. package/dist/providers/cloudflare-ai-gateway.js +24 -1
  19. package/dist/providers/cloudflare-workers-ai.d.ts +7 -0
  20. package/dist/providers/cloudflare-workers-ai.js +31 -5
  21. package/dist/providers/digitalocean.d.ts +9 -0
  22. package/dist/providers/digitalocean.js +16 -2
  23. package/dist/providers/opencode.js +1 -0
  24. package/dist/providers/openrouter.js +1 -0
  25. package/dist/providers/typesafe-ai.js +1 -0
  26. package/dist/providers/vercel-ai-gateway.d.ts +3 -0
  27. package/dist/providers/vercel-ai-gateway.js +6 -1
  28. package/dist/route/media-protocol.d.ts +1 -0
  29. package/dist/route/media-protocol.js +12 -8
  30. package/dist/utils/media-type.js +18 -1
  31. package/package.json +3 -3
package/README.md CHANGED
@@ -186,18 +186,32 @@ console.log(response.answers.refund.probability)
186
186
  `OPENCODE_API_KEY`. OpenRouter, Vercel AI Gateway, and OpenAI use the same provider shape:
187
187
 
188
188
  ```ts
189
- import { OpenAI, OpenRouter, VercelAIGateway } from "@opencode/ai/providers"
189
+ import { Baseten, DigitalOcean, OpenAI, OpenRouter, VercelAIGateway } from "@opencode/ai/providers"
190
190
 
191
191
  OpenRouter.configure().experimental.evaluation("typesafe/jev-1.13")
192
192
  VercelAIGateway.configure().experimental.evaluation("typesafe-ai/jev")
193
+ Baseten.configure().experimental.evaluation("decision-models/baseten-elephant-9b-latest")
194
+ DigitalOcean.configure().experimental.evaluation("typesafe-jev-1.13.0")
193
195
  OpenAI.configure().experimental.evaluation("gpt-6-luna")
194
196
  ```
195
197
 
196
198
  OpenRouter reads `OPENROUTER_API_KEY`. Vercel reads `AI_GATEWAY_API_KEY`, then `VERCEL_OIDC_TOKEN`.
199
+ Baseten reads `BASETEN_API_KEY`, accepts `max_len` in `options`, and returns unrounded values, so
200
+ `response.rounding` is unset. DigitalOcean reads
201
+ `DIGITALOCEAN_ACCESS_TOKEN`, `DIGITALOCEAN_API_KEY`, then `DO_INFERENCE_API_KEY`.
197
202
  OpenAI reads `OPENAI_API_KEY` and calls `/v1/decisions`.
198
203
  The common API uses `boolean`; System One routes lower it to native `noul`, and OpenAI lowers it to
199
204
  `predicate`. OpenAI predicates take no criteria, so boolean criteria fail before the request, and a
200
205
  refused question fails the call with a `ContentPolicy` error.
206
+ Cloudflare serves its Clef models through Workers AI and TypeSafe Jev through AI Gateway, both on `/ai/run`:
207
+
208
+ ```ts
209
+ import { CloudflareAIGateway, CloudflareWorkersAI } from "@opencode/ai/providers"
210
+
211
+ CloudflareWorkersAI.configure({ accountId }).experimental.evaluation("@cf/cloudflare/clef")
212
+ CloudflareAIGateway.configure({ accountId }).experimental.evaluation("typesafe/jev")
213
+ ```
214
+
201
215
  Choice and score answers include `confidence` when the provider returns it, such as
202
216
  `response.answers.department.confidence`. Score legends remain available in provider metadata, and
203
217
  the provider's rounded probabilities are returned unchanged.
@@ -274,6 +288,14 @@ Package entrypoints are `@opencode/ai/providers/alibaba`, `alibaba/chat`, `aliba
274
288
  and `alibaba/responses`. Live recordings cover all three APIs in Singapore; regional URL construction
275
289
  is unit-tested for all six regions.
276
290
 
291
+ ### Images
292
+
293
+ `alibaba.image(...)` uses the native multimodal generation API (`/api/v1/services/aigc/multimodal-generation/generation`)
294
+ for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `size` lowers to
295
+ `W*H`, and `images` are sent as URLs or data URLs for editing. Native `parameters` include `negativePrompt`,
296
+ `promptExtend`, `watermark`, `thinkingMode`, and `enableSequential`; raw keys such as `bbox_list` or `size: "2K"`
297
+ pass through. Results are URLs that Model Studio keeps for 24 hours. A complete `baseURL` for images includes `/api/v1`.
298
+
277
299
  ## Z.AI
278
300
 
279
301
  `ZAI` uses the standard API. Chat Completions is the default language-model API;
@@ -551,15 +573,20 @@ call rather than being dropped, so check this table before swapping only the `mo
551
573
  | Google (Gemini) | 1 | ✗ | ✓ | ✓ | ✗ | ✓ (no public URLs) | ✗ |
552
574
  | xAI | ✓ | ✗ | ✓ | ✗ | ✗ | ✓ | ✗ |
553
575
  | Z.ai | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
576
+ | Alibaba | ✓ | ✓ | ✗ | ✓ | ✗ | ✓ | ✗ |
554
577
  | Meta | ✓ | ✓ (hint) | ✗ | ✗ | ✓ | ✓ | ✗ |
555
578
  | Black Forest Labs | 1 | per model | per model | ✓ | ✓ | per model (1–8) | `flux-pro-1.0-fill` |
556
579
  | fal | ✓ | per model | per model | ✓ | ✓ | 1 (several on `/edit`, `/multi`) | ✓ |
557
580
  | Replicate | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ (use `providerOptions`) | ✗ |
558
581
  | Stability `image` | 1 | ✗ | ✓ | ✓ | ✓ | 1 (not on `core`) | ✗ |
559
582
  | Stability `upscale()` | ✗ | ✗ | ✗ | ✓ | ✓ | exactly 1 (required) | ✗ |
583
+ | Vercel AI Gateway | ✓ | per model | ✗ | ✗ | ignored | per model | per model |
584
+ | Cloudflare Workers AI | 1 | ✓² | ✗ | ✓² | ✗ | ✗ | ✗ |
560
585
 
561
586
  ✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. ¹ `Image.stream` on OpenAI generates one image. fal
562
- rejects `size` and `aspectRatio` together; which one a fal or BFL model takes depends on the model.
587
+ rejects `size` and `aspectRatio` together; which one a fal or BFL model takes depends on the model. Vercel AI Gateway
588
+ forwards `format` but does not apply it, so the returned bytes keep the upstream model's own format. ² Workers AI
589
+ `@cf/black-forest-labs/flux-1-schnell` takes neither `size` nor `seed`, and the provider rejects them.
563
590
 
564
591
  `Media.Asset` is the one asset type shared by image requests, image responses, LLM messages, and tool results.
565
592
  `asset.source` is the serializable `Media.Source` (`bytes`, `base64`, `url`, or `ref`); `asset.bytes()`,
@@ -0,0 +1,15 @@
1
+ import { EvaluationModel, type EvaluationRounding } from "./evaluation.js";
2
+ import { MediaRoute } from "../route/media.js";
3
+ import type { ProviderID } from "../schema/index.js";
4
+ export interface ModelInput extends MediaRoute.ModelInput {
5
+ /** Also the provider metadata key. */
6
+ readonly provider: ProviderID;
7
+ /** The Run API base, `.../client/v4/accounts/{account}/ai/run`. */
8
+ readonly baseURL: string;
9
+ readonly rounding?: EvaluationRounding;
10
+ }
11
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One request body as `input`. */
12
+ export declare const model: (input: ModelInput) => EvaluationModel<import("./evaluation.js").EvaluationOptions>;
13
+ export declare const CloudflareRunEvaluation: {
14
+ readonly model: typeof model;
15
+ };
@@ -0,0 +1,43 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { EvaluationModel, } from "./evaluation.js";
3
+ import { SystemOne } from "./system-one.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { MediaRoute } from "../route/media.js";
7
+ // Workers AI models answer with the System One response; third-party models such as TypeSafe Jev wrap it in a
8
+ // completed run record.
9
+ const Envelope = Schema.Struct({
10
+ result: Schema.Union([
11
+ SystemOne.Response,
12
+ Schema.Struct({ state: Schema.Literal("Completed"), result: SystemOne.Response }),
13
+ ]),
14
+ });
15
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One request body as `input`. */
16
+ export const model = (input) => {
17
+ const route = MediaProtocol.identity({
18
+ id: "cloudflare-run-evaluation",
19
+ name: "Cloudflare Run",
20
+ provider: input.provider,
21
+ });
22
+ const decodeEnvelope = route.decodeJson(Envelope);
23
+ const composed = MediaRoute.inline({
24
+ protocol: MediaProtocol.inline(route, {
25
+ body: {
26
+ from: (request) => SystemOne.encodeInput(request).pipe(Effect.map((body) => MediaProtocol.json({ model: request.model.id, input: body }))),
27
+ },
28
+ response: {
29
+ decode: (response) => decodeEnvelope(response).pipe(Effect.map((output) => SystemOne.toResponse("answers" in output.value.result ? output.value.result : output.value.result.result, input.provider, input.rounding))),
30
+ },
31
+ }),
32
+ endpoint: Endpoint.path("", { baseURL: input.baseURL }),
33
+ auth: input.auth,
34
+ headers: input.headers,
35
+ });
36
+ return EvaluationModel.make({
37
+ id: input.id,
38
+ provider: input.provider,
39
+ http: input.http,
40
+ route: { id: composed.id, evaluate: composed.generate },
41
+ });
42
+ };
43
+ export const CloudflareRunEvaluation = { model };
@@ -1,6 +1,32 @@
1
- import { EvaluationModel, type EvaluationOptions } from "./evaluation.js";
1
+ import { Effect, Schema } from "effect";
2
+ import { EvaluationModel, EvaluationResponse, EvaluationRounding, type EvaluationOptions, type EvaluationRequestFor } from "./evaluation.js";
2
3
  import { type Definition as AuthDefinition } from "../route/auth.js";
3
- import { HttpOptions, ModelID } from "../schema/index.js";
4
+ import { AIError, HttpOptions, ModelID } from "../schema/index.js";
5
+ export declare const Response: Schema.Struct<{
6
+ readonly model: Schema.String;
7
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
8
+ readonly type: Schema.Literal<"noul">;
9
+ readonly noul: Schema.Number;
10
+ }>, Schema.Struct<{
11
+ readonly type: Schema.Literal<"choice">;
12
+ readonly choice: Schema.String;
13
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
14
+ readonly confidence: Schema.optional<Schema.Number>;
15
+ }>, Schema.Struct<{
16
+ readonly type: Schema.Literal<"score">;
17
+ readonly score: Schema.Number;
18
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
19
+ readonly legend: Schema.optional<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
20
+ readonly confidence: Schema.optional<Schema.Number>;
21
+ }>]>>;
22
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
23
+ readonly input_tokens: Schema.optional<Schema.Number>;
24
+ readonly output_tokens: Schema.optional<Schema.Number>;
25
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
26
+ readonly id: Schema.optional<Schema.String>;
27
+ readonly provider: Schema.optional<Schema.String>;
28
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
29
+ }>;
4
30
  export interface ModelInput {
5
31
  readonly id: string | ModelID;
6
32
  readonly provider: string;
@@ -9,8 +35,80 @@ export interface ModelInput {
9
35
  readonly baseURL: string;
10
36
  readonly headers?: Record<string, string>;
11
37
  readonly http?: HttpOptions;
38
+ readonly rounding?: EvaluationRounding;
12
39
  }
40
+ export declare const jevRounding: EvaluationRounding;
41
+ /** The System One request body without `model`, with `boolean` questions lowered to native `noul`. */
42
+ export declare const encodeInput: (req: EvaluationRequestFor) => Effect.Effect<{
43
+ readonly [x: string]: unknown;
44
+ readonly state: string | readonly Schema.Json[] | {
45
+ readonly [x: string]: Schema.Json;
46
+ };
47
+ readonly questions: {
48
+ readonly [x: string]: {
49
+ readonly type: "choice";
50
+ readonly instructions: string | readonly Schema.Json[] | {
51
+ readonly [x: string]: Schema.Json;
52
+ };
53
+ readonly criteria: {
54
+ readonly [x: string]: string | readonly Schema.Json[] | {
55
+ readonly [x: string]: Schema.Json;
56
+ } | null;
57
+ };
58
+ } | {
59
+ readonly type: "score";
60
+ readonly instructions: string | readonly Schema.Json[] | {
61
+ readonly [x: string]: Schema.Json;
62
+ };
63
+ readonly criteria: readonly (string | readonly Schema.Json[] | {
64
+ readonly [x: string]: Schema.Json;
65
+ } | null)[];
66
+ } | {
67
+ readonly type: "noul";
68
+ readonly instructions: string | readonly Schema.Json[] | {
69
+ readonly [x: string]: Schema.Json;
70
+ };
71
+ readonly criteria?: {
72
+ readonly true?: string | readonly Schema.Json[] | {
73
+ readonly [x: string]: Schema.Json;
74
+ } | null | undefined;
75
+ readonly false?: string | readonly Schema.Json[] | {
76
+ readonly [x: string]: Schema.Json;
77
+ } | null | undefined;
78
+ } | undefined;
79
+ };
80
+ };
81
+ }, AIError, never>;
82
+ export declare const toResponse: (data: typeof Response.Type, providerMetadataKey: string, rounding?: EvaluationRounding) => EvaluationResponse;
13
83
  export declare const model: <Options extends EvaluationOptions = EvaluationOptions>(cfg: ModelInput) => EvaluationModel<Options>;
14
84
  export declare const SystemOne: {
85
+ readonly Response: Schema.Struct<{
86
+ readonly model: Schema.String;
87
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
88
+ readonly type: Schema.Literal<"noul">;
89
+ readonly noul: Schema.Number;
90
+ }>, Schema.Struct<{
91
+ readonly type: Schema.Literal<"choice">;
92
+ readonly choice: Schema.String;
93
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
94
+ readonly confidence: Schema.optional<Schema.Number>;
95
+ }>, Schema.Struct<{
96
+ readonly type: Schema.Literal<"score">;
97
+ readonly score: Schema.Number;
98
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
99
+ readonly legend: Schema.optional<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
100
+ readonly confidence: Schema.optional<Schema.Number>;
101
+ }>]>>;
102
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
103
+ readonly input_tokens: Schema.optional<Schema.Number>;
104
+ readonly output_tokens: Schema.optional<Schema.Number>;
105
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
106
+ readonly id: Schema.optional<Schema.String>;
107
+ readonly provider: Schema.optional<Schema.String>;
108
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
109
+ }>;
110
+ readonly encodeInput: typeof encodeInput;
111
+ readonly toResponse: typeof toResponse;
15
112
  readonly model: typeof model;
113
+ readonly jevRounding: EvaluationRounding;
16
114
  };
@@ -5,6 +5,7 @@ import { Auth } from "../route/auth.js";
5
5
  import { RequestExecutor } from "../route/executor.js";
6
6
  import { JsonObject, ProviderShared } from "../protocols/shared.js";
7
7
  import { AIError, HttpOptions, InvalidProviderOutputError, InvalidRequestError, ModelID, ProviderMetadata, Usage, mergeJsonRecords, } from "../schema/index.js";
8
+ import { encodeJson } from "../utils/json.js";
8
9
  const Noul = Schema.Struct({
9
10
  type: Schema.Literal("noul"),
10
11
  instructions: EvaluationInput,
@@ -22,8 +23,7 @@ const Question = Schema.Union([
22
23
  })),
23
24
  Noul,
24
25
  ]);
25
- const Request = Schema.StructWithRest(Schema.Struct({
26
- model: Schema.String,
26
+ const Input = Schema.StructWithRest(Schema.Struct({
27
27
  state: EvaluationInput,
28
28
  questions: Schema.Record(Schema.String, Question),
29
29
  }), [JsonObject]);
@@ -47,7 +47,7 @@ const NativeUsage = Schema.StructWithRest(Schema.Struct({
47
47
  input_tokens: Schema.optional(Schema.Number),
48
48
  output_tokens: Schema.optional(Schema.Number),
49
49
  }), [JsonObject]);
50
- const Response = Schema.Struct({
50
+ export const Response = Schema.Struct({
51
51
  model: Schema.String,
52
52
  answers: Schema.Record(Schema.String, Answer),
53
53
  usage: Schema.optional(NativeUsage),
@@ -55,6 +55,62 @@ const Response = Schema.Struct({
55
55
  provider: Schema.optional(Schema.String),
56
56
  provider_metadata: Schema.optional(ProviderMetadata),
57
57
  });
58
+ export const jevRounding = new EvaluationRounding({ probabilityDecimals: 2, scoreDecimals: 2 });
59
+ /** The System One request body without `model`, with `boolean` questions lowered to native `noul`. */
60
+ export const encodeInput = (req) => Schema.encodeUnknownEffect(Input)({
61
+ ...mergeJsonRecords(req.options, req.http?.body),
62
+ state: req.state,
63
+ questions: Object.fromEntries(Object.entries(req.questions).map(([id, x]) => [id, x.type === "boolean" ? { ...x, type: "noul" } : x])),
64
+ }).pipe(Effect.mapError((cause) => new AIError({ reason: new InvalidRequestError({ message: cause.message, cause }) })));
65
+ export const toResponse = (data, providerMetadataKey, rounding) => {
66
+ const legend = {};
67
+ const answers = Object.fromEntries(Object.entries(data.answers).map(([id, answer]) => {
68
+ if (answer.type === "noul")
69
+ return [id, { type: "boolean", probability: answer.noul }];
70
+ if (answer.type === "choice") {
71
+ return [
72
+ id,
73
+ {
74
+ type: "choice",
75
+ choice: answer.choice,
76
+ probabilities: answer.probabilities,
77
+ ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
78
+ },
79
+ ];
80
+ }
81
+ if (answer.legend !== undefined)
82
+ legend[id] = answer.legend;
83
+ return [
84
+ id,
85
+ {
86
+ type: "score",
87
+ score: answer.score,
88
+ probabilities: answer.probabilities,
89
+ ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
90
+ },
91
+ ];
92
+ }));
93
+ const meta = {
94
+ ...(data.id === undefined ? {} : { responseId: data.id }),
95
+ ...(data.provider === undefined ? {} : { provider: data.provider }),
96
+ ...data.provider_metadata?.[providerMetadataKey],
97
+ ...(Object.keys(legend).length === 0 ? {} : { legend }),
98
+ };
99
+ return new EvaluationResponse({
100
+ model: ModelID.make(data.model),
101
+ answers,
102
+ usage: data.usage
103
+ ? new Usage({
104
+ inputTokens: data.usage.input_tokens,
105
+ outputTokens: data.usage.output_tokens,
106
+ totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
107
+ providerMetadata: { [providerMetadataKey]: data.usage },
108
+ })
109
+ : undefined,
110
+ rounding,
111
+ providerMetadata: Object.keys(meta).length === 0 ? undefined : { [providerMetadataKey]: meta },
112
+ });
113
+ };
58
114
  export const model = (cfg) => EvaluationModel.make({
59
115
  id: cfg.id,
60
116
  provider: cfg.provider,
@@ -64,12 +120,7 @@ export const model = (cfg) => EvaluationModel.make({
64
120
  evaluate: (req, send) => Effect.gen(function* () {
65
121
  const url = new URL(`${cfg.baseURL.replace(/\/$/, "")}/systemone`);
66
122
  Object.entries(req.http?.query ?? {}).forEach(([key, value]) => url.searchParams.set(key, value));
67
- const body = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(Request))({
68
- ...mergeJsonRecords(req.options, req.http?.body),
69
- model: req.model.id,
70
- state: req.state,
71
- questions: Object.fromEntries(Object.entries(req.questions).map(([id, x]) => [id, x.type === "boolean" ? { ...x, type: "noul" } : x])),
72
- }).pipe(Effect.mapError((cause) => new AIError({ reason: new InvalidRequestError({ message: cause.message, cause }) })));
123
+ const body = encodeJson({ ...(yield* encodeInput(req)), model: req.model.id });
73
124
  const headers = yield* Auth.toEffect(cfg.auth)({
74
125
  request: req,
75
126
  method: "POST",
@@ -82,54 +133,8 @@ export const model = (cfg) => EvaluationModel.make({
82
133
  const fail = (message, cause, body) => new AIError({ reason: new InvalidProviderOutputError({ route: "system-one", message, body, http, cause }) });
83
134
  const text = yield* res.text.pipe(Effect.mapError((cause) => fail("Failed to read the System One response", cause)));
84
135
  const data = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Response))(text).pipe(Effect.mapError((cause) => fail("System One returned an invalid response", cause, text)));
85
- const legend = {};
86
- const answers = Object.fromEntries(Object.entries(data.answers).map(([id, answer]) => {
87
- if (answer.type === "noul")
88
- return [id, { type: "boolean", probability: answer.noul }];
89
- if (answer.type === "choice") {
90
- return [
91
- id,
92
- {
93
- type: "choice",
94
- choice: answer.choice,
95
- probabilities: answer.probabilities,
96
- ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
97
- },
98
- ];
99
- }
100
- if (answer.legend !== undefined)
101
- legend[id] = answer.legend;
102
- return [
103
- id,
104
- {
105
- type: "score",
106
- score: answer.score,
107
- probabilities: answer.probabilities,
108
- ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
109
- },
110
- ];
111
- }));
112
- const meta = {
113
- ...(data.id === undefined ? {} : { responseId: data.id }),
114
- ...(data.provider === undefined ? {} : { provider: data.provider }),
115
- ...data.provider_metadata?.[cfg.providerMetadataKey],
116
- ...(Object.keys(legend).length === 0 ? {} : { legend }),
117
- };
118
- return new EvaluationResponse({
119
- model: ModelID.make(data.model),
120
- answers,
121
- usage: data.usage
122
- ? new Usage({
123
- inputTokens: data.usage.input_tokens,
124
- outputTokens: data.usage.output_tokens,
125
- totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
126
- providerMetadata: { [cfg.providerMetadataKey]: data.usage },
127
- })
128
- : undefined,
129
- rounding: new EvaluationRounding({ probabilityDecimals: 2, scoreDecimals: 2 }),
130
- providerMetadata: Object.keys(meta).length === 0 ? undefined : { [cfg.providerMetadataKey]: meta },
131
- });
136
+ return toResponse(data, cfg.providerMetadataKey, cfg.rounding);
132
137
  }),
133
138
  },
134
139
  });
135
- export const SystemOne = { model };
140
+ export const SystemOne = { Response, encodeInput, toResponse, model, jevRounding };
@@ -0,0 +1,19 @@
1
+ import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ export declare const PATH = "/services/aigc/multimodal-generation/generation";
5
+ /** Provider-native `parameters`. Common fields (`n`, `size`, `seed`, `images`) live on the request. */
6
+ export type AlibabaImageOptions = {
7
+ readonly negativePrompt?: string;
8
+ readonly promptExtend?: boolean;
9
+ readonly watermark?: boolean;
10
+ readonly thinkingMode?: boolean;
11
+ readonly enableSequential?: boolean;
12
+ } & Record<string, unknown>;
13
+ export type Request = ImageRequestFor<AlibabaImageOptions>;
14
+ export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
15
+ export declare const model: (input: MediaRoute.ModelInput) => ImageModel<AlibabaImageOptions>;
16
+ export declare const AlibabaImages: {
17
+ readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
18
+ readonly model: typeof model;
19
+ };
@@ -0,0 +1,76 @@
1
+ import { Duration, Effect, Schema } from "effect";
2
+ import { ImageModel, ImageResponse } from "../image.js";
3
+ import { MediaProtocol } from "../route/media-protocol.js";
4
+ import { MediaRoute } from "../route/media.js";
5
+ import { mergeJsonRecords } from "../schema/index.js";
6
+ import { JsonObject, ProviderShared, lenient } from "./shared.js";
7
+ const route = MediaProtocol.identity({ id: "alibaba-images", name: "Alibaba Images", provider: "alibaba" });
8
+ export const PATH = "/services/aigc/multimodal-generation/generation";
9
+ const OUTPUT_RETENTION = Duration.hours(24);
10
+ // ---------------------------------------------------------------------------
11
+ // 2. Response schema
12
+ // ---------------------------------------------------------------------------
13
+ const AlibabaImageResponse = Schema.Struct({
14
+ output: Schema.Struct({
15
+ choices: Schema.Array(Schema.Struct({
16
+ message: Schema.Struct({
17
+ content: Schema.Array(Schema.Struct({ image: Schema.optional(Schema.String) })),
18
+ }),
19
+ })),
20
+ }),
21
+ usage: lenient(JsonObject),
22
+ request_id: Schema.optional(Schema.String),
23
+ });
24
+ // ---------------------------------------------------------------------------
25
+ // 5. Request body construction
26
+ // ---------------------------------------------------------------------------
27
+ const nativeOptions = (options) => {
28
+ if (!options)
29
+ return undefined;
30
+ const { negativePrompt, promptExtend, thinkingMode, enableSequential, ...native } = options;
31
+ return {
32
+ negative_prompt: negativePrompt,
33
+ prompt_extend: promptExtend,
34
+ thinking_mode: thinkingMode,
35
+ enable_sequential: enableSequential,
36
+ ...native,
37
+ };
38
+ };
39
+ const fromRequest = Effect.fn("AlibabaImages.fromRequest")(function* (request) {
40
+ const images = yield* Effect.forEach(request.images ?? [], (image) => ProviderShared.mediaReference(image, undefined, `${route.name} input`).pipe(Effect.map((item) => ({ image: item.value }))));
41
+ return MediaProtocol.json(mergeJsonRecords({
42
+ model: request.model.id,
43
+ input: { messages: [{ role: "user", content: [...images, { text: request.prompt }] }] },
44
+ parameters: mergeJsonRecords({ size: request.size?.replace("x", "*"), n: request.n, seed: request.seed }, nativeOptions(request.providerOptions)),
45
+ }, request.http?.body) ?? {});
46
+ });
47
+ // ---------------------------------------------------------------------------
48
+ // 6. Response decoding
49
+ // ---------------------------------------------------------------------------
50
+ const decodeDocument = route.decodeJson(AlibabaImageResponse);
51
+ const decodeResponse = Effect.fn("AlibabaImages.decodeResponse")(function* (response) {
52
+ const output = yield* decodeDocument(response);
53
+ const decoded = output.value;
54
+ // Qwen-Image returns every image in one choice; Wan returns one choice per image.
55
+ const urls = decoded.output.choices.flatMap((choice) => choice.message.content.flatMap((item) => (item.image === undefined ? [] : [item.image])));
56
+ if (urls.length === 0)
57
+ return yield* output.invalid(`${route.name} returned no images`);
58
+ // Model Studio bills per image; its token counts are informational, so the raw record stays in provider metadata.
59
+ return new ImageResponse({
60
+ images: yield* Effect.forEach(urls, (url) => MediaProtocol.expiringUrl(url, OUTPUT_RETENTION)),
61
+ providerMetadata: { alibaba: { requestID: decoded.request_id, usage: decoded.usage } },
62
+ });
63
+ });
64
+ // ---------------------------------------------------------------------------
65
+ // 7. Protocol and route
66
+ // ---------------------------------------------------------------------------
67
+ export const protocol = MediaProtocol.inline(route, {
68
+ unsupported: ["mask", "aspectRatio", "format"],
69
+ body: { from: fromRequest },
70
+ response: { decode: decodeResponse },
71
+ });
72
+ export const model = (input) => ImageModel.fromRoute({ protocol, path: PATH }, input);
73
+ export const AlibabaImages = {
74
+ protocol,
75
+ model,
76
+ };
@@ -0,0 +1,17 @@
1
+ import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import type { MediaRoute } from "../route/media.js";
4
+ /** Native Run API inputs. Step counts are `steps` on FLUX and Lucid Origin and `num_steps` on the other models. */
5
+ export type CloudflareWorkersAIImageOptions = {
6
+ readonly steps?: number;
7
+ readonly num_steps?: number;
8
+ readonly guidance?: number;
9
+ readonly negative_prompt?: string;
10
+ } & Record<string, unknown>;
11
+ export type Request = ImageRequestFor<CloudflareWorkersAIImageOptions>;
12
+ export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
13
+ export declare const model: (input: MediaRoute.ModelInput) => ImageModel<CloudflareWorkersAIImageOptions>;
14
+ export declare const CloudflareWorkersAIImages: {
15
+ readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
16
+ readonly model: typeof model;
17
+ };
@@ -0,0 +1,72 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { ImageModel, ImageResponse } from "../image.js";
3
+ import { Media } from "../media.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { mergeJsonRecords } from "../schema/index.js";
6
+ import { MediaInput } from "./utils/media-input.js";
7
+ const route = MediaProtocol.identity({
8
+ id: "cloudflare-workers-ai-images",
9
+ name: "Cloudflare Workers AI",
10
+ provider: "cloudflare-workers-ai",
11
+ });
12
+ /** FLUX.2 models only accept multipart form fields, even for a prompt alone. */
13
+ const MULTIPART_MODEL_PREFIX = "@cf/black-forest-labs/flux-2-";
14
+ const RESERVED_FORM_FIELDS = new Set(["prompt"]);
15
+ // ---------------------------------------------------------------------------
16
+ // 2. Response schema
17
+ // ---------------------------------------------------------------------------
18
+ const RunResponse = Schema.Struct({
19
+ result: Schema.Struct({
20
+ image: Schema.optional(Schema.String),
21
+ usage: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
22
+ }),
23
+ });
24
+ // ---------------------------------------------------------------------------
25
+ // 5. Request body construction
26
+ // ---------------------------------------------------------------------------
27
+ const fromRequest = Effect.fn("CloudflareWorkersAIImages.fromRequest")(function* (request) {
28
+ if (request.n !== undefined && request.n > 1)
29
+ return yield* route.unsupported("media.n", `${route.name} generates one image per request; call it once per image`);
30
+ const fields = {
31
+ prompt: request.prompt,
32
+ ...(request.size === undefined ? {} : MediaInput.dimensions(request.size)),
33
+ seed: request.seed,
34
+ };
35
+ const native = mergeJsonRecords(request.providerOptions, request.http?.body);
36
+ if (!request.model.id.startsWith(MULTIPART_MODEL_PREFIX))
37
+ return MediaProtocol.json(mergeJsonRecords(fields, native) ?? {});
38
+ const body = new FormData();
39
+ MediaInput.appendFields(body, fields, { overlay: native, reserved: RESERVED_FORM_FIELDS });
40
+ return MediaProtocol.multipart(body);
41
+ });
42
+ // ---------------------------------------------------------------------------
43
+ // 6. Response decoding
44
+ // ---------------------------------------------------------------------------
45
+ const decodeDocument = route.decodeJson(RunResponse);
46
+ // FLUX and Lucid Origin wrap base64 in the Run API envelope; the Stable Diffusion family, DreamShaper, and Phoenix
47
+ // answer with the raw image, whose declared content type does not always match the bytes.
48
+ const decodeResponse = Effect.fn("CloudflareWorkersAIImages.decodeResponse")(function* (response) {
49
+ if (!response.headers["content-type"]?.startsWith("application/json"))
50
+ return new ImageResponse({ images: [Media.bytes(yield* route.bytes(response))] });
51
+ const output = yield* decodeDocument(response);
52
+ const result = output.value.result;
53
+ if (result.image === undefined)
54
+ return yield* output.invalid(`${route.name} returned no image`);
55
+ return new ImageResponse({
56
+ images: [yield* MediaInput.decodedAsset(output.invalid, `${route.name} result`, result.image, undefined)],
57
+ providerMetadata: result.usage === undefined ? undefined : { "cloudflare-workers-ai": { usage: result.usage } },
58
+ });
59
+ });
60
+ // ---------------------------------------------------------------------------
61
+ // 7. Protocol and route
62
+ // ---------------------------------------------------------------------------
63
+ export const protocol = MediaProtocol.inline(route, {
64
+ unsupported: ["images", "mask", "aspectRatio", "format"],
65
+ body: { from: fromRequest },
66
+ response: { decode: decodeResponse },
67
+ });
68
+ export const model = (input) => ImageModel.fromRoute({ protocol, path: ({ request }) => `/${request.model.id}` }, input);
69
+ export const CloudflareWorkersAIImages = {
70
+ protocol,
71
+ model,
72
+ };
@@ -1,8 +1,9 @@
1
+ import { Schema } from "effect";
1
2
  import { ImageModel, type ImageRequestFor } from "../image.js";
2
3
  import { Media } from "../media.js";
3
4
  import { MediaProtocol } from "../route/media-protocol.js";
4
5
  import { MediaRoute } from "../route/media.js";
5
- import { type MediaUsage, type OpenString } from "../schema/index.js";
6
+ import { type OpenString } from "../schema/index.js";
6
7
  export declare const DEFAULT_BASE_URL = "https://api.openai.com/v1";
7
8
  export declare const PATH = "/images/generations";
8
9
  export declare const EDIT_PATH = "/images/edits";
@@ -16,10 +17,16 @@ export type OpenAIImageOptions = {
16
17
  readonly partialImages?: number;
17
18
  } & Record<string, unknown>;
18
19
  export type Request = ImageRequestFor<OpenAIImageOptions>;
19
- /** `generate` reads the whole JSON response as one frame, with the requested format for responses that omit it. */
20
+ declare const Usage: Schema.Struct<{
21
+ readonly input_tokens: Schema.optional<Schema.Number>;
22
+ readonly output_tokens: Schema.optional<Schema.Number>;
23
+ readonly total_tokens: Schema.optional<Schema.Number>;
24
+ readonly input_tokens_details: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
25
+ readonly output_tokens_details: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
26
+ }>;
27
+ /** `generate` reads the whole JSON response as one frame. */
20
28
  type Frame = string | {
21
29
  readonly document: string;
22
- readonly requested: string | undefined;
23
30
  };
24
31
  interface State {
25
32
  readonly completed: number;
@@ -27,7 +34,7 @@ interface State {
27
34
  readonly size?: string;
28
35
  readonly quality?: string;
29
36
  readonly background?: string;
30
- readonly usage?: MediaUsage;
37
+ readonly usage?: Schema.Schema.Type<typeof Usage>;
31
38
  }
32
39
  export declare const protocol: MediaProtocol.Streamed<Request, {
33
40
  readonly type: "image-partial";
@@ -83,7 +90,10 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
83
90
  };
84
91
  } | undefined;
85
92
  }, Frame, State>;
86
- export declare const model: (input: MediaRoute.ModelInput) => ImageModel<OpenAIImageOptions>;
93
+ /** `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. */
94
+ export declare const model: (input: MediaRoute.ModelInput & {
95
+ readonly provider?: string;
96
+ }) => ImageModel<OpenAIImageOptions>;
87
97
  export declare const OpenAIImages: {
88
98
  readonly protocol: MediaProtocol.Streamed<Request, {
89
99
  readonly type: "image-partial";