@opencode/ai 2.1.4 → 2.2.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/README.md +339 -166
- package/dist/ai-client.d.ts +2 -2
- package/dist/ai-client.js +2 -1
- package/dist/cache-policy.d.ts +4 -0
- package/dist/cache-policy.js +20 -6
- package/dist/decision-client.d.ts +21 -0
- package/dist/decision-client.js +55 -0
- package/dist/decision.d.ts +472 -0
- package/dist/decision.js +158 -0
- package/dist/effect.d.ts +38 -0
- package/dist/effect.js +27 -0
- package/dist/effort-updates.d.ts +2 -2
- package/dist/experimental/cloudflare-run-extraction.d.ts +13 -0
- package/dist/experimental/cloudflare-run-extraction.js +83 -0
- package/dist/experimental/extraction.d.ts +183 -0
- package/dist/experimental/extraction.js +102 -0
- package/dist/experimental/realtime.d.ts +7 -2
- package/dist/experimental/realtime.js +5 -5
- package/dist/experimental.d.ts +2 -3
- package/dist/experimental.js +1 -2
- package/dist/image-client.d.ts +50 -14
- package/dist/image-client.js +0 -1
- package/dist/image.d.ts +6 -176
- package/dist/image.js +4 -11
- package/dist/index.d.ts +1444 -34
- package/dist/index.js +139 -24
- package/dist/llm.d.ts +16 -1
- package/dist/llm.js +34 -0
- package/dist/media-client.d.ts +3 -1
- package/dist/media-client.js +1 -0
- package/dist/media-model.d.ts +3 -0
- package/dist/media-model.js +4 -1
- package/dist/media.d.ts +0 -7
- package/dist/media.js +0 -6
- package/dist/protocols/alibaba-chat.d.ts +59 -4
- package/dist/protocols/alibaba-images.d.ts +22 -0
- package/dist/protocols/alibaba-images.js +77 -0
- package/dist/protocols/alibaba-messages.d.ts +52 -17
- package/dist/protocols/alibaba-responses.d.ts +26 -6
- package/dist/protocols/anthropic-messages.d.ts +160 -54
- package/dist/protocols/anthropic-messages.js +44 -13
- package/dist/protocols/bedrock-converse.d.ts +110 -15
- package/dist/protocols/bedrock-converse.js +112 -15
- package/dist/protocols/bedrock-event-stream.js +1 -0
- package/dist/protocols/cartesia-speech.d.ts +0 -18
- package/dist/protocols/cloudflare-run-decisions.d.ts +9 -0
- package/dist/protocols/cloudflare-run-decisions.js +36 -0
- package/dist/protocols/cloudflare-workers-ai-images.d.ts +23 -0
- package/dist/protocols/cloudflare-workers-ai-images.js +80 -0
- package/dist/protocols/deepgram-speech.d.ts +0 -18
- package/dist/protocols/elevenlabs-speech.d.ts +0 -18
- package/dist/protocols/gemini.d.ts +3 -0
- package/dist/protocols/gemini.js +11 -6
- package/dist/protocols/google-images.d.ts +2 -2
- package/dist/protocols/google-images.js +10 -37
- package/dist/protocols/google-interactions.d.ts +4 -0
- package/dist/protocols/google-interactions.js +12 -5
- package/dist/protocols/google-speech.d.ts +0 -18
- package/dist/protocols/google-speech.js +0 -1
- package/dist/protocols/google-transcription.d.ts +0 -18
- package/dist/protocols/google-transcription.js +0 -1
- package/dist/protocols/google-video.d.ts +1 -1
- package/dist/protocols/google-video.js +2 -7
- package/dist/protocols/index.d.ts +3 -0
- package/dist/protocols/index.js +3 -0
- package/dist/protocols/meta-images.d.ts +7 -1
- package/dist/protocols/meta-images.js +10 -8
- package/dist/protocols/meta-messages.d.ts +52 -17
- package/dist/protocols/meta-messages.js +14 -1
- package/dist/protocols/meta-responses.d.ts +46 -6
- package/dist/protocols/meta-responses.js +29 -1
- package/dist/protocols/minimax-images.d.ts +25 -0
- package/dist/protocols/minimax-images.js +150 -0
- package/dist/protocols/open-responses.d.ts +212 -27
- package/dist/protocols/open-responses.js +116 -54
- package/dist/protocols/openai-chat.d.ts +1135 -31
- package/dist/protocols/openai-chat.js +155 -60
- package/dist/protocols/openai-compatible-chat.d.ts +57 -5
- package/dist/protocols/openai-compatible-responses.d.ts +28 -8
- package/dist/protocols/openai-decisions.d.ts +22 -0
- package/dist/protocols/openai-decisions.js +128 -0
- package/dist/protocols/openai-freeform.d.ts +47 -0
- package/dist/protocols/openai-freeform.js +54 -0
- package/dist/protocols/openai-images.d.ts +36 -24
- package/dist/protocols/openai-images.js +137 -39
- package/dist/protocols/openai-responses.d.ts +202 -42
- package/dist/protocols/openai-responses.js +49 -10
- package/dist/protocols/openai-speech.d.ts +0 -18
- package/dist/protocols/openai-speech.js +15 -5
- package/dist/protocols/openai-transcription.d.ts +0 -18
- package/dist/protocols/openai-transcription.js +3 -4
- package/dist/protocols/runway-video.d.ts +1 -1
- package/dist/protocols/runway-video.js +1 -1
- package/dist/protocols/shared.d.ts +9 -1
- package/dist/protocols/shared.js +13 -2
- package/dist/protocols/system-one.d.ts +101 -0
- package/dist/protocols/system-one.js +230 -0
- package/dist/protocols/utils/bedrock-cache.d.ts +2 -2
- package/dist/protocols/utils/bedrock-cache.js +7 -6
- package/dist/protocols/utils/cache.d.ts +14 -3
- package/dist/protocols/utils/cache.js +11 -4
- package/dist/protocols/utils/gemini-generate-content.d.ts +3 -3
- package/dist/protocols/utils/gemini-generate-content.js +10 -16
- package/dist/protocols/utils/gemini-json-schema.d.ts +5 -0
- package/dist/protocols/utils/gemini-json-schema.js +3 -3
- package/dist/protocols/utils/image-sizing.d.ts +31 -0
- package/dist/protocols/utils/image-sizing.js +73 -0
- package/dist/protocols/utils/media-input.d.ts +4 -5
- package/dist/protocols/utils/media-input.js +8 -5
- package/dist/protocols/utils/speech-stream.d.ts +0 -1
- package/dist/protocols/utils/speech-stream.js +0 -1
- package/dist/protocols/utils/tool-schema.js +15 -5
- package/dist/protocols/utils/tool-stream.d.ts +9 -0
- package/dist/protocols/venice-chat.d.ts +58 -4
- package/dist/protocols/venice-chat.js +2 -2
- package/dist/protocols/xai-images.d.ts +7 -2
- package/dist/protocols/xai-images.js +11 -5
- package/dist/protocols/xai-responses.d.ts +30 -3
- package/dist/protocols/xai-responses.js +30 -3
- package/dist/protocols/xai-video.d.ts +1 -1
- package/dist/protocols/xai-video.js +11 -8
- package/dist/protocols/zai-chat.d.ts +60 -4
- package/dist/protocols/zai-images.d.ts +3 -1
- package/dist/protocols/zai-images.js +12 -11
- package/dist/protocols/zai-messages.d.ts +52 -17
- package/dist/provider-error.js +23 -7
- package/dist/provider-package.d.ts +2 -0
- package/dist/providers/alibaba/images.d.ts +2 -0
- package/dist/providers/alibaba/images.js +1 -0
- package/dist/providers/alibaba.d.ts +137 -28
- package/dist/providers/alibaba.js +16 -8
- package/dist/providers/amazon-bedrock-mantle.d.ts +259 -145
- package/dist/providers/amazon-bedrock-mantle.js +1 -1
- package/dist/providers/amazon-bedrock.d.ts +34 -14
- package/dist/providers/amazon-bedrock.js +11 -11
- package/dist/providers/anthropic-compatible.d.ts +53 -18
- package/dist/providers/anthropic.d.ts +53 -18
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/azure/images.d.ts +2 -0
- package/dist/providers/azure/images.js +1 -0
- package/dist/providers/azure.d.ts +129 -24
- package/dist/providers/azure.js +19 -1
- package/dist/providers/baseten/decisions.d.ts +2 -0
- package/dist/providers/baseten/decisions.js +1 -0
- package/dist/providers/baseten.d.ts +124 -12
- package/dist/providers/baseten.js +41 -8
- package/dist/providers/cerebras.d.ts +115 -11
- package/dist/providers/cerebras.js +1 -1
- package/dist/providers/cloudflare-ai-gateway/decisions.d.ts +2 -0
- package/dist/providers/cloudflare-ai-gateway/decisions.js +1 -0
- package/dist/providers/cloudflare-ai-gateway.d.ts +290 -60
- package/dist/providers/cloudflare-ai-gateway.js +32 -4
- package/dist/providers/cloudflare-workers-ai/decisions.d.ts +2 -0
- package/dist/providers/cloudflare-workers-ai/decisions.js +1 -0
- package/dist/providers/cloudflare-workers-ai/images.d.ts +2 -0
- package/dist/providers/cloudflare-workers-ai/images.js +1 -0
- package/dist/providers/cloudflare-workers-ai.d.ts +128 -12
- package/dist/providers/cloudflare-workers-ai.js +45 -9
- package/dist/providers/cohere/chat.d.ts +1 -1
- package/dist/providers/cohere/chat.js +1 -1
- package/dist/providers/cohere.d.ts +115 -11
- package/dist/providers/cohere.js +1 -1
- package/dist/providers/deepinfra.d.ts +115 -11
- package/dist/providers/deepinfra.js +1 -1
- package/dist/providers/deepseek.d.ts +115 -11
- package/dist/providers/deepseek.js +1 -1
- package/dist/providers/digitalocean/decisions.d.ts +2 -0
- package/dist/providers/digitalocean/decisions.js +1 -0
- package/dist/providers/digitalocean/images.d.ts +2 -0
- package/dist/providers/digitalocean/images.js +1 -0
- package/dist/providers/digitalocean/responses.d.ts +4 -0
- package/dist/providers/digitalocean/responses.js +1 -0
- package/dist/providers/digitalocean.d.ts +390 -20
- package/dist/providers/digitalocean.js +53 -11
- package/dist/providers/fireworks.d.ts +115 -11
- package/dist/providers/fireworks.js +1 -1
- package/dist/providers/google/images.d.ts +2 -0
- package/dist/providers/google/images.js +1 -0
- package/dist/providers/google/interactions.d.ts +1 -1
- package/dist/providers/google/interactions.js +1 -1
- package/dist/providers/google-vertex/images.d.ts +2 -0
- package/dist/providers/google-vertex/images.js +1 -0
- package/dist/providers/google-vertex-chat.d.ts +57 -5
- package/dist/providers/google-vertex-chat.js +1 -1
- package/dist/providers/google-vertex-interactions.d.ts +1 -1
- package/dist/providers/google-vertex-interactions.js +1 -1
- package/dist/providers/google-vertex-messages.d.ts +53 -18
- package/dist/providers/google-vertex-messages.js +1 -1
- package/dist/providers/google-vertex-mistral.d.ts +1 -1
- package/dist/providers/google-vertex-mistral.js +1 -1
- package/dist/providers/google-vertex-responses.d.ts +24 -4
- package/dist/providers/google-vertex-responses.js +1 -1
- package/dist/providers/google-vertex.d.ts +4 -2
- package/dist/providers/google-vertex.js +30 -13
- package/dist/providers/google.d.ts +6 -5
- package/dist/providers/google.js +15 -8
- package/dist/providers/groq.d.ts +119 -15
- package/dist/providers/groq.js +1 -7
- package/dist/providers/index.d.ts +0 -4
- package/dist/providers/index.js +0 -4
- package/dist/providers/meta/images.d.ts +2 -0
- package/dist/providers/meta/images.js +1 -0
- package/dist/providers/meta.d.ts +254 -146
- package/dist/providers/meta.js +2 -1
- package/dist/providers/minimax/chat.d.ts +1 -1
- package/dist/providers/minimax/chat.js +1 -1
- package/dist/providers/minimax/images.d.ts +3 -0
- package/dist/providers/minimax/images.js +1 -0
- package/dist/providers/minimax/responses.d.ts +1 -1
- package/dist/providers/minimax/responses.js +1 -1
- package/dist/providers/minimax.d.ts +139 -26
- package/dist/providers/minimax.js +22 -9
- package/dist/providers/mistral.d.ts +3 -3
- package/dist/providers/mistral.js +1 -1
- package/dist/providers/moonshot/messages.d.ts +1 -1
- package/dist/providers/moonshot/messages.js +1 -1
- package/dist/providers/moonshot/responses.d.ts +1 -1
- package/dist/providers/moonshot/responses.js +1 -1
- package/dist/providers/moonshot.d.ts +132 -25
- package/dist/providers/moonshot.js +1 -1
- package/dist/providers/openai/images.d.ts +2 -0
- package/dist/providers/openai/images.js +1 -0
- package/dist/providers/openai-compatible/images.d.ts +2 -0
- package/dist/providers/openai-compatible/images.js +1 -0
- package/dist/providers/openai-compatible-responses.d.ts +24 -4
- package/dist/providers/openai-compatible.d.ts +62 -8
- package/dist/providers/openai-compatible.js +29 -10
- package/dist/providers/openai-options.d.ts +3 -1
- package/dist/providers/openai.d.ts +103 -18
- package/dist/providers/openai.js +23 -5
- package/dist/providers/opencode/decisions.d.ts +2 -0
- package/dist/providers/opencode/decisions.js +1 -0
- package/dist/providers/opencode.d.ts +11 -12
- package/dist/providers/opencode.js +10 -8
- package/dist/providers/openrouter/decisions.d.ts +2 -0
- package/dist/providers/openrouter/decisions.js +1 -0
- package/dist/providers/openrouter/images.d.ts +2 -0
- package/dist/providers/openrouter/images.js +1 -0
- package/dist/providers/openrouter/responses.d.ts +4 -0
- package/dist/providers/openrouter/responses.js +1 -0
- package/dist/providers/openrouter.d.ts +446 -35
- package/dist/providers/openrouter.js +78 -27
- package/dist/providers/togetherai.d.ts +115 -11
- package/dist/providers/togetherai.js +1 -1
- package/dist/providers/typesafe-ai/decisions.d.ts +2 -0
- package/dist/providers/typesafe-ai/decisions.js +1 -0
- package/dist/providers/typesafe-ai.d.ts +11 -12
- package/dist/providers/typesafe-ai.js +10 -8
- package/dist/providers/venice/responses.d.ts +4 -0
- package/dist/providers/venice/responses.js +1 -0
- package/dist/providers/venice.d.ts +261 -9
- package/dist/providers/venice.js +33 -17
- package/dist/providers/vercel-ai-gateway/decisions.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/decisions.js +1 -0
- package/dist/providers/vercel-ai-gateway/images.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/images.js +1 -0
- package/dist/providers/vercel-ai-gateway.d.ts +16 -22
- package/dist/providers/vercel-ai-gateway.js +41 -85
- package/dist/providers/xai/images.d.ts +2 -0
- package/dist/providers/xai/images.js +1 -0
- package/dist/providers/xai.d.ts +66 -12
- package/dist/providers/xai.js +15 -8
- package/dist/providers/zai/images.d.ts +2 -0
- package/dist/providers/zai/images.js +1 -0
- package/dist/providers/zai-coding-plan/messages.d.ts +1 -1
- package/dist/providers/zai-coding-plan/messages.js +1 -1
- package/dist/providers/zai-coding-plan/responses.d.ts +1 -1
- package/dist/providers/zai-coding-plan/responses.js +1 -1
- package/dist/providers/zai-coding-plan.d.ts +132 -25
- package/dist/providers/zai-coding-plan.js +1 -1
- package/dist/providers/zai.d.ts +62 -9
- package/dist/providers/zai.js +15 -8
- package/dist/route/auth.d.ts +1 -1
- package/dist/route/client.d.ts +2 -2
- package/dist/route/client.js +26 -4
- package/dist/route/decision.d.ts +58 -0
- package/dist/route/decision.js +75 -0
- package/dist/route/executor.d.ts +1 -1
- package/dist/route/framing.d.ts +2 -0
- package/dist/route/index.d.ts +3 -0
- package/dist/route/index.js +3 -0
- package/dist/route/media-protocol.d.ts +3 -4
- package/dist/route/media-protocol.js +12 -8
- package/dist/route/media.d.ts +6 -2
- package/dist/route/media.js +8 -6
- package/dist/route/transport/http.js +1 -0
- package/dist/route/transport/index.d.ts +1 -0
- package/dist/schema/events.d.ts +148 -6
- package/dist/schema/events.js +20 -0
- package/dist/schema/messages.d.ts +41 -3
- package/dist/schema/messages.js +23 -0
- package/dist/schema/options.d.ts +5 -3
- package/dist/schema/options.js +8 -3
- package/dist/speech-client.d.ts +53 -14
- package/dist/speech-client.js +0 -1
- package/dist/speech.d.ts +0 -135
- package/dist/speech.js +2 -4
- package/dist/testing/decision.d.ts +16 -0
- package/dist/testing/decision.js +20 -0
- package/dist/testing/image.d.ts +14 -0
- package/dist/testing/image.js +12 -0
- package/dist/testing/media.d.ts +18 -0
- package/dist/testing/media.js +36 -0
- package/dist/testing/script.d.ts +28 -0
- package/dist/testing/script.js +60 -0
- package/dist/testing/speech.d.ts +14 -0
- package/dist/testing/speech.js +12 -0
- package/dist/testing/transcription.d.ts +14 -0
- package/dist/testing/transcription.js +12 -0
- package/dist/testing/video.d.ts +14 -0
- package/dist/testing/video.js +12 -0
- package/dist/testing.d.ts +35 -45
- package/dist/testing.js +14 -75
- package/dist/tool.d.ts +12 -1
- package/dist/tool.js +10 -2
- package/dist/transcription-client.d.ts +69 -14
- package/dist/transcription.d.ts +0 -135
- package/dist/transcription.js +1 -1
- package/dist/utils/media-type.js +22 -1
- package/dist/video-client.d.ts +46 -14
- package/dist/video-client.js +0 -1
- package/dist/video.d.ts +1 -136
- package/dist/video.js +3 -5
- package/package.json +497 -11
- package/dist/experimental/evaluation-client.d.ts +0 -21
- package/dist/experimental/evaluation-client.js +0 -64
- package/dist/experimental/evaluation.d.ts +0 -242
- package/dist/experimental/evaluation.js +0 -108
- package/dist/experimental/system-one.d.ts +0 -16
- package/dist/experimental/system-one.js +0 -135
- package/dist/promise.d.ts +0 -1021
- package/dist/promise.js +0 -101
- package/dist/protocols/bfl-images.d.ts +0 -38
- package/dist/protocols/bfl-images.js +0 -153
- package/dist/protocols/fal-images.d.ts +0 -25
- package/dist/protocols/fal-images.js +0 -104
- package/dist/protocols/fal-video.d.ts +0 -29
- package/dist/protocols/fal-video.js +0 -73
- package/dist/protocols/replicate-images.d.ts +0 -28
- package/dist/protocols/replicate-images.js +0 -127
- package/dist/protocols/stability-images.d.ts +0 -39
- package/dist/protocols/stability-images.js +0 -136
- package/dist/protocols/utils/fal-queue.d.ts +0 -26
- package/dist/protocols/utils/fal-queue.js +0 -67
- package/dist/provider.d.ts +0 -23
- package/dist/provider.js +0 -2
- package/dist/providers/black-forest-labs.d.ts +0 -21
- package/dist/providers/black-forest-labs.js +0 -23
- package/dist/providers/fal.d.ts +0 -24
- package/dist/providers/fal.js +0 -26
- package/dist/providers/replicate.d.ts +0 -21
- package/dist/providers/replicate.js +0 -17
- package/dist/providers/stability.d.ts +0 -23
- package/dist/providers/stability.js +0 -18
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { Effect, Schema } from "effect";
|
|
2
|
+
import { DecisionResponse, DecisionUsage } 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, message: Schema.optional(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"
|
|
89
|
+
? {
|
|
90
|
+
name: answer.name,
|
|
91
|
+
type: "error",
|
|
92
|
+
reason: "refusal",
|
|
93
|
+
...(answer.message === undefined ? {} : { message: answer.message }),
|
|
94
|
+
}
|
|
95
|
+
: answer);
|
|
96
|
+
const byName = new Map(answers.map((answer) => [answer.name, answer]));
|
|
97
|
+
const ordered = context.request.questions.flatMap((question) => byName.get(question.name) ?? []);
|
|
98
|
+
const usage = OpenResponses.mapUsage(output.value.usage, context.providerMetadataKey);
|
|
99
|
+
return new DecisionResponse({
|
|
100
|
+
answers: ordered.length === answers.length ? ordered : answers,
|
|
101
|
+
usage: usage === undefined
|
|
102
|
+
? undefined
|
|
103
|
+
: new DecisionUsage({
|
|
104
|
+
inputTokens: usage.inputTokens,
|
|
105
|
+
outputTokens: usage.outputTokens,
|
|
106
|
+
totalTokens: usage.totalTokens,
|
|
107
|
+
cost: usage.cost,
|
|
108
|
+
}),
|
|
109
|
+
providerMetadata: {
|
|
110
|
+
[context.providerMetadataKey]: {
|
|
111
|
+
model: output.value.model,
|
|
112
|
+
...(output.value.usage === undefined ? {} : { usage: output.value.usage }),
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}),
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
export const route = DecisionRoute.make({
|
|
120
|
+
id: ID,
|
|
121
|
+
provider: "openai",
|
|
122
|
+
protocol,
|
|
123
|
+
endpoint: Endpoint.path(PATH, { baseURL: DEFAULT_BASE_URL }),
|
|
124
|
+
});
|
|
125
|
+
export const OpenAIDecisions = {
|
|
126
|
+
protocol,
|
|
127
|
+
route,
|
|
128
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { ToolDefinition, type Freeform, type LLMEvent, type LLMRequest, type ProviderMetadata } from "../schema/index.js";
|
|
2
|
+
import { ToolStream } from "./utils/tool-stream.js";
|
|
3
|
+
export interface Custom {
|
|
4
|
+
/** The tool's one required string parameter, which the raw text fills. */
|
|
5
|
+
readonly field: string;
|
|
6
|
+
readonly format: Freeform;
|
|
7
|
+
}
|
|
8
|
+
/** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
|
|
9
|
+
export declare const resolve: (tool: ToolDefinition) => Custom | undefined;
|
|
10
|
+
/** Custom tools in this request, by flattened tool name. */
|
|
11
|
+
export declare const tools: (request: LLMRequest) => ReadonlyMap<string, Custom>;
|
|
12
|
+
/** The format's grammar, or `undefined` for unconstrained text. */
|
|
13
|
+
export declare const grammar: (format: Freeform) => {
|
|
14
|
+
syntax: "lark" | "regex";
|
|
15
|
+
definition: string;
|
|
16
|
+
} | undefined;
|
|
17
|
+
/** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
|
|
18
|
+
export declare const toRaw: (custom: Custom, input: unknown) => string;
|
|
19
|
+
/** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
|
|
20
|
+
export declare const fromRaw: (custom: Custom | undefined, raw: string) => string;
|
|
21
|
+
/** The opening fragment, `{"field":"`, followed by the escaped first text. */
|
|
22
|
+
export declare const streamStart: (custom: Custom | undefined, raw?: string) => string;
|
|
23
|
+
export declare const streamDelta: (raw: string) => string;
|
|
24
|
+
/**
|
|
25
|
+
* Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
|
|
26
|
+
* decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
|
|
27
|
+
*/
|
|
28
|
+
export declare const close: <K extends string | number>(tools: ToolStream.State<K>, keys: Iterable<K>, final?: {
|
|
29
|
+
readonly custom: Custom | undefined;
|
|
30
|
+
readonly raw: string;
|
|
31
|
+
}) => {
|
|
32
|
+
readonly tools: ToolStream.State<K>;
|
|
33
|
+
readonly events: ReadonlyArray<LLMEvent>;
|
|
34
|
+
};
|
|
35
|
+
/** Provider metadata marking a call that arrived as a custom tool call. */
|
|
36
|
+
export declare const metadata: (itemId: string, custom: boolean) => {
|
|
37
|
+
itemId: string;
|
|
38
|
+
custom: boolean;
|
|
39
|
+
} | {
|
|
40
|
+
itemId: string;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Whether a replayed call keeps its item id: only when it goes out as the type it arrived as, since OpenAI item ids
|
|
44
|
+
* name their type (`fc_`, `ctc_`). The `call_id` always survives.
|
|
45
|
+
*/
|
|
46
|
+
export declare const keepsItemID: (providerMetadata: ProviderMetadata | undefined, key: string, custom: boolean) => boolean;
|
|
47
|
+
export * as OpenAIFreeform from "./openai-freeform.js";
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
|
+
import { ToolDefinition, } from "../schema/index.js";
|
|
3
|
+
import { encodeJson, flattenTools, isRecord } from "./shared.js";
|
|
4
|
+
import { ToolStream } from "./utils/tool-stream.js";
|
|
5
|
+
/** How a tool goes out: a custom tool when it declares `freeform` with one required string parameter. */
|
|
6
|
+
export const resolve = (tool) => {
|
|
7
|
+
const field = ToolDefinition.freeformField(tool.inputSchema);
|
|
8
|
+
if (tool.freeform === undefined || tool.native !== undefined || field === undefined)
|
|
9
|
+
return undefined;
|
|
10
|
+
return { field, format: tool.freeform };
|
|
11
|
+
};
|
|
12
|
+
/** Custom tools in this request, by flattened tool name. */
|
|
13
|
+
export const tools = (request) => new Map(flattenTools(request.tools).flatMap((tool) => {
|
|
14
|
+
const custom = resolve(tool);
|
|
15
|
+
return custom ? [[tool.name, custom]] : [];
|
|
16
|
+
}));
|
|
17
|
+
/** The format's grammar, or `undefined` for unconstrained text. */
|
|
18
|
+
export const grammar = (format) => format.type === "text"
|
|
19
|
+
? undefined
|
|
20
|
+
: { syntax: format.type, definition: format.type === "regex" ? format.pattern : format.grammar };
|
|
21
|
+
/** Raw text replayed for a past call: its field, or the whole input as JSON when the field is not a string. */
|
|
22
|
+
export const toRaw = (custom, input) => {
|
|
23
|
+
const value = isRecord(input) ? input[custom.field] : undefined;
|
|
24
|
+
return typeof value === "string" ? value : encodeJson(input ?? {});
|
|
25
|
+
};
|
|
26
|
+
/** JSON arguments for a raw call. A call to an undeclared custom tool fills `input`. */
|
|
27
|
+
export const fromRaw = (custom, raw) => encodeJson({ [field(custom)]: raw });
|
|
28
|
+
const field = (custom) => custom?.field ?? "input";
|
|
29
|
+
// Streamed raw text is re-encoded as JSON-argument fragments, so the tool-input events match a JSON tool's.
|
|
30
|
+
/** The opening fragment, `{"field":"`, followed by the escaped first text. */
|
|
31
|
+
export const streamStart = (custom, raw = "") => `{${encodeJson(field(custom))}:"${streamDelta(raw)}`;
|
|
32
|
+
export const streamDelta = (raw) => encodeJson(raw).slice(1, -1);
|
|
33
|
+
const STREAM_END = '"}';
|
|
34
|
+
const decodeArguments = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)));
|
|
35
|
+
/**
|
|
36
|
+
* Close the JSON fragment of each open custom call. With a `final` raw input, a call only closes when its fragments
|
|
37
|
+
* decode to it, so an authoritative final input that disagrees replaces the streamed one instead.
|
|
38
|
+
*/
|
|
39
|
+
export const close = (tools, keys, final) => [...keys].reduce((result, key) => {
|
|
40
|
+
const pending = result.tools[key];
|
|
41
|
+
const streamed = pending && Option.getOrUndefined(decodeArguments(`${pending.input}${STREAM_END}`));
|
|
42
|
+
if (!pending || (final !== undefined && streamed?.[field(final.custom)] !== final.raw))
|
|
43
|
+
return result;
|
|
44
|
+
const appended = ToolStream.append(result.tools, key, STREAM_END);
|
|
45
|
+
return appended ? { tools: appended.tools, events: [...result.events, ...appended.events] } : result;
|
|
46
|
+
}, { tools, events: [] });
|
|
47
|
+
/** Provider metadata marking a call that arrived as a custom tool call. */
|
|
48
|
+
export const metadata = (itemId, custom) => (custom ? { itemId, custom: true } : { itemId });
|
|
49
|
+
/**
|
|
50
|
+
* Whether a replayed call keeps its item id: only when it goes out as the type it arrived as, since OpenAI item ids
|
|
51
|
+
* name their type (`fc_`, `ctc_`). The `call_id` always survives.
|
|
52
|
+
*/
|
|
53
|
+
export const keepsItemID = (providerMetadata, key, custom) => (providerMetadata?.[key]?.custom === true) === custom;
|
|
54
|
+
export * as OpenAIFreeform from "./openai-freeform.js";
|
|
@@ -1,13 +1,19 @@
|
|
|
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
|
|
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";
|
|
9
|
-
/** Provider-native options. Common fields (`n`, `
|
|
10
|
+
/** Provider-native options. Common fields (`n`, `aspect`, `resolution`, `images`) live on the request. */
|
|
10
11
|
export type OpenAIImageOptions = {
|
|
12
|
+
/** Exact `WIDTHxHEIGHT` or `auto`; it replaces `aspect` and `resolution`, so setting both fails. */
|
|
13
|
+
readonly size?: OpenString<"auto" | "1024x1024" | "1536x1024" | "1024x1536">;
|
|
14
|
+
readonly outputFormat?: OpenString<"png" | "jpeg" | "webp">;
|
|
15
|
+
/** Inpainting mask for the first input image. */
|
|
16
|
+
readonly mask?: Media.Asset;
|
|
11
17
|
readonly quality?: OpenString<"auto" | "low" | "medium" | "high" | "standard" | "hd">;
|
|
12
18
|
readonly background?: OpenString<"auto" | "opaque" | "transparent">;
|
|
13
19
|
readonly moderation?: OpenString<"auto" | "low">;
|
|
@@ -16,10 +22,16 @@ export type OpenAIImageOptions = {
|
|
|
16
22
|
readonly partialImages?: number;
|
|
17
23
|
} & Record<string, unknown>;
|
|
18
24
|
export type Request = ImageRequestFor<OpenAIImageOptions>;
|
|
19
|
-
|
|
25
|
+
declare const Usage: Schema.Struct<{
|
|
26
|
+
readonly input_tokens: Schema.optional<Schema.Number>;
|
|
27
|
+
readonly output_tokens: Schema.optional<Schema.Number>;
|
|
28
|
+
readonly total_tokens: Schema.optional<Schema.Number>;
|
|
29
|
+
readonly input_tokens_details: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
|
|
30
|
+
readonly output_tokens_details: Schema.optional<Schema.$Record<Schema.String, Schema.Unknown>>;
|
|
31
|
+
}>;
|
|
32
|
+
/** `generate` reads the whole JSON response as one frame. */
|
|
20
33
|
type Frame = string | {
|
|
21
34
|
readonly document: string;
|
|
22
|
-
readonly requested: string | undefined;
|
|
23
35
|
};
|
|
24
36
|
interface State {
|
|
25
37
|
readonly completed: number;
|
|
@@ -27,8 +39,17 @@ interface State {
|
|
|
27
39
|
readonly size?: string;
|
|
28
40
|
readonly quality?: string;
|
|
29
41
|
readonly background?: string;
|
|
30
|
-
readonly usage?:
|
|
42
|
+
readonly usage?: Schema.Schema.Type<typeof Usage>;
|
|
31
43
|
}
|
|
44
|
+
/** The body fields `aspect` and `resolution` lower to; gateways that read other fields than `size` pass their own. */
|
|
45
|
+
export type OpenAIImageSizing = (request: Request) => Record<string, unknown> | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* How input images travel. `edits` is OpenAI's `/images/edits`, uploading owned bytes as multipart; `json-edits` sends
|
|
48
|
+
* every edit there as JSON with data URLs, for hosts that reject multipart (the ChatGPT backend); `references` keeps
|
|
49
|
+
* every request on `/images/generations` and lists them as `input_references`, for gateways without an edits endpoint
|
|
50
|
+
* (OpenRouter).
|
|
51
|
+
*/
|
|
52
|
+
export type OpenAIImageInput = "edits" | "json-edits" | "references";
|
|
32
53
|
export declare const protocol: MediaProtocol.Streamed<Request, {
|
|
33
54
|
readonly type: "image-partial";
|
|
34
55
|
readonly index: number;
|
|
@@ -68,22 +89,21 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
|
|
|
68
89
|
readonly [x: string]: unknown;
|
|
69
90
|
} | undefined;
|
|
70
91
|
} | undefined;
|
|
71
|
-
readonly notices?: readonly {
|
|
72
|
-
readonly type: "filtered" | "moderated" | "other";
|
|
73
|
-
readonly message: string;
|
|
74
|
-
readonly providerMetadata?: {
|
|
75
|
-
readonly [x: string]: {
|
|
76
|
-
readonly [x: string]: unknown;
|
|
77
|
-
};
|
|
78
|
-
} | undefined;
|
|
79
|
-
}[] | undefined;
|
|
80
92
|
readonly providerMetadata?: {
|
|
81
93
|
readonly [x: string]: {
|
|
82
94
|
readonly [x: string]: unknown;
|
|
83
95
|
};
|
|
84
96
|
} | undefined;
|
|
85
97
|
}, Frame, State>;
|
|
86
|
-
|
|
98
|
+
/**
|
|
99
|
+
* `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. `sizing`
|
|
100
|
+
* replaces the `size` that `aspect` and `resolution` lower to, and `imageInput` how input images are sent.
|
|
101
|
+
*/
|
|
102
|
+
export declare const model: (input: MediaRoute.ModelInput & {
|
|
103
|
+
readonly provider?: string;
|
|
104
|
+
readonly sizing?: OpenAIImageSizing;
|
|
105
|
+
readonly imageInput?: OpenAIImageInput;
|
|
106
|
+
}) => ImageModel<OpenAIImageOptions>;
|
|
87
107
|
export declare const OpenAIImages: {
|
|
88
108
|
readonly protocol: MediaProtocol.Streamed<Request, {
|
|
89
109
|
readonly type: "image-partial";
|
|
@@ -124,15 +144,6 @@ export declare const OpenAIImages: {
|
|
|
124
144
|
readonly [x: string]: unknown;
|
|
125
145
|
} | undefined;
|
|
126
146
|
} | undefined;
|
|
127
|
-
readonly notices?: readonly {
|
|
128
|
-
readonly type: "filtered" | "moderated" | "other";
|
|
129
|
-
readonly message: string;
|
|
130
|
-
readonly providerMetadata?: {
|
|
131
|
-
readonly [x: string]: {
|
|
132
|
-
readonly [x: string]: unknown;
|
|
133
|
-
};
|
|
134
|
-
} | undefined;
|
|
135
|
-
}[] | undefined;
|
|
136
147
|
readonly providerMetadata?: {
|
|
137
148
|
readonly [x: string]: {
|
|
138
149
|
readonly [x: string]: unknown;
|
|
@@ -140,5 +151,6 @@ export declare const OpenAIImages: {
|
|
|
140
151
|
} | undefined;
|
|
141
152
|
}, Frame, State>;
|
|
142
153
|
readonly model: typeof model;
|
|
154
|
+
readonly pixelSize: OpenAIImageSizing;
|
|
143
155
|
};
|
|
144
156
|
export {};
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import { Effect, Schema, Stream } from "effect";
|
|
1
|
+
import { Effect, Schema, SchemaGetter, Stream } from "effect";
|
|
2
2
|
import { ImageFinishEvent, ImageModel, ImageOutputEvent, ImagePartialEvent, } from "../image.js";
|
|
3
3
|
import { Media } from "../media.js";
|
|
4
|
+
import { classifyProviderFailure } from "../provider-error.js";
|
|
4
5
|
import { Framing } from "../route/framing.js";
|
|
5
6
|
import { MediaProtocol } from "../route/media-protocol.js";
|
|
6
7
|
import { MediaRoute } from "../route/media.js";
|
|
7
|
-
import { mergeJsonRecords } from "../schema/index.js";
|
|
8
|
-
import { ProviderShared } from "./shared.js";
|
|
8
|
+
import { AIError, mergeJsonRecords, ProviderID, tokenUsage } from "../schema/index.js";
|
|
9
|
+
import { optionalNull, ProviderShared } from "./shared.js";
|
|
10
|
+
import { ImageSizing } from "./utils/image-sizing.js";
|
|
9
11
|
import { MediaInput } from "./utils/media-input.js";
|
|
10
12
|
const route = MediaProtocol.identity({ id: "openai-images", name: "OpenAI Images", provider: "openai" });
|
|
11
13
|
export const DEFAULT_BASE_URL = "https://api.openai.com/v1";
|
|
@@ -29,13 +31,28 @@ const Settings = {
|
|
|
29
31
|
background: Schema.optional(Schema.String),
|
|
30
32
|
};
|
|
31
33
|
const OpenAIImageResponse = Schema.Struct({
|
|
32
|
-
|
|
34
|
+
// GPT Image models always return `b64_json`; compatible hosts that default to `url` can return either.
|
|
35
|
+
data: Schema.Array(Schema.Struct({ b64_json: optionalNull(Schema.String), url: optionalNull(Schema.String) })),
|
|
33
36
|
...Settings,
|
|
34
37
|
usage: Schema.optional(Usage),
|
|
35
38
|
});
|
|
36
39
|
// ---------------------------------------------------------------------------
|
|
37
40
|
// 3. Streaming event schema
|
|
38
41
|
// ---------------------------------------------------------------------------
|
|
42
|
+
const EVENT_TYPES = new Set([
|
|
43
|
+
"image_generation.partial_image",
|
|
44
|
+
"image_edit.partial_image",
|
|
45
|
+
"image_generation.completed",
|
|
46
|
+
"image_edit.completed",
|
|
47
|
+
"error",
|
|
48
|
+
]);
|
|
49
|
+
/** OpenAI may add stream event types; frames outside `EVENT_TYPES` are ignored, while a malformed known type still fails decoding. */
|
|
50
|
+
const UnknownEvent = Schema.Struct({
|
|
51
|
+
type: Schema.String.check(Schema.makeFilter((type) => !EVENT_TYPES.has(type))),
|
|
52
|
+
}).pipe(Schema.decodeTo(Schema.Struct({ type: Schema.Literal("unknown"), rawType: Schema.String }), {
|
|
53
|
+
decode: SchemaGetter.transform((event) => ({ type: "unknown", rawType: event.type })),
|
|
54
|
+
encode: SchemaGetter.forbidden(() => "Unknown OpenAI Images stream events are decode-only"),
|
|
55
|
+
}));
|
|
39
56
|
const StreamEvent = Schema.Union([
|
|
40
57
|
Schema.Struct({
|
|
41
58
|
type: Schema.Literals(["image_generation.partial_image", "image_edit.partial_image"]),
|
|
@@ -51,6 +68,11 @@ const StreamEvent = Schema.Union([
|
|
|
51
68
|
output_format: Schema.String,
|
|
52
69
|
usage: Schema.optional(Usage),
|
|
53
70
|
}),
|
|
71
|
+
Schema.Struct({
|
|
72
|
+
type: Schema.Literal("error"),
|
|
73
|
+
error: Schema.optional(Schema.Struct({ message: Schema.optional(Schema.String) })),
|
|
74
|
+
}),
|
|
75
|
+
UnknownEvent,
|
|
54
76
|
]);
|
|
55
77
|
const decodeEvent = route.decodeFrame(StreamEvent);
|
|
56
78
|
const decodeDocument = Schema.decodeUnknownEffect(Schema.fromJsonString(OpenAIImageResponse));
|
|
@@ -62,8 +84,45 @@ const RESERVED_FORM_FIELDS = new Set(["model", "prompt", "image", "image[]", "im
|
|
|
62
84
|
const nativeOptions = (options) => {
|
|
63
85
|
if (!options)
|
|
64
86
|
return undefined;
|
|
65
|
-
const { outputCompression, partialImages: _, ...native } = options;
|
|
66
|
-
|
|
87
|
+
const { outputCompression, outputFormat, partialImages: _, mask: __, ...native } = options;
|
|
88
|
+
// `response_format: null` drops a provider's default, for hosts that reject the field.
|
|
89
|
+
return {
|
|
90
|
+
output_compression: outputCompression,
|
|
91
|
+
output_format: outputFormat,
|
|
92
|
+
...native,
|
|
93
|
+
response_format: native.response_format ?? undefined,
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* `gpt-image-1`, `chatgpt-image` and DALL·E take a fixed list, `gpt-image-2` and later any size within limits. Other
|
|
98
|
+
* models are gateway-hosted (`bfl/flux-2-pro`); the gateway passes `size` through to them as is.
|
|
99
|
+
*/
|
|
100
|
+
const sizes = (model) => {
|
|
101
|
+
const id = model.slice(model.lastIndexOf("/") + 1);
|
|
102
|
+
if (id.startsWith("dall-e-2"))
|
|
103
|
+
return [256, 512, 1024].map((edge) => ({ width: edge, height: edge }));
|
|
104
|
+
if (id.startsWith("dall-e-3"))
|
|
105
|
+
return [
|
|
106
|
+
{ width: 1024, height: 1024 },
|
|
107
|
+
{ width: 1792, height: 1024 },
|
|
108
|
+
{ width: 1024, height: 1792 },
|
|
109
|
+
];
|
|
110
|
+
if (/^(gpt-image-1|chatgpt-image)/.test(id))
|
|
111
|
+
return [
|
|
112
|
+
{ width: 1024, height: 1024 },
|
|
113
|
+
{ width: 1536, height: 1024 },
|
|
114
|
+
{ width: 1024, height: 1536 },
|
|
115
|
+
];
|
|
116
|
+
if (id.startsWith("gpt-image-"))
|
|
117
|
+
return { multiple: 16, maxEdge: 3840, minPixels: 655_360, maxPixels: 8_294_400, maxRatio: 3 };
|
|
118
|
+
return { multiple: 16 };
|
|
119
|
+
};
|
|
120
|
+
const pixelSize = (request) => {
|
|
121
|
+
if (!ImageSizing.isRequested(request))
|
|
122
|
+
return undefined;
|
|
123
|
+
const options = sizes(request.model.id);
|
|
124
|
+
const size = "multiple" in options ? ImageSizing.fit(request, options) : ImageSizing.nearest(request, options);
|
|
125
|
+
return { size: `${size.width}x${size.height}` };
|
|
67
126
|
};
|
|
68
127
|
const streamOptions = (request) => {
|
|
69
128
|
if (request.mode !== "stream")
|
|
@@ -74,15 +133,36 @@ const streamOptions = (request) => {
|
|
|
74
133
|
};
|
|
75
134
|
const isEdit = (request) => (request.images?.length ?? 0) > 0;
|
|
76
135
|
const isInline = (asset) => asset.source.type === "bytes" || asset.source.type === "base64";
|
|
77
|
-
const reference = (asset) => ProviderShared.mediaReference(asset,
|
|
78
|
-
const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
|
|
136
|
+
const reference = (asset, provider) => ProviderShared.mediaReference(asset, provider, route.name).pipe(Effect.map((item) => (item.type === "ref" ? { file_id: item.value } : { image_url: item.value })));
|
|
137
|
+
const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request, options) {
|
|
79
138
|
const images = request.images ?? [];
|
|
80
|
-
const mask = request.mask;
|
|
139
|
+
const mask = request.providerOptions?.mask;
|
|
140
|
+
if (options.imageInput === "references" && mask !== undefined)
|
|
141
|
+
return yield* route.unsupported("media.mask", `${request.model.provider} image edits take no mask`);
|
|
81
142
|
if (mask !== undefined && images.length === 0)
|
|
82
143
|
return yield* ProviderShared.invalidRequest("An OpenAI image mask requires at least one input image");
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
144
|
+
if (request.providerOptions?.size !== undefined && ImageSizing.isRequested(request))
|
|
145
|
+
return yield* ProviderShared.invalidRequest("OpenAI providerOptions.size replaces aspect and resolution; set one or the other");
|
|
146
|
+
const fields = mergeJsonRecords({
|
|
147
|
+
n: request.n,
|
|
148
|
+
...options.sizing(request),
|
|
149
|
+
...(yield* streamOptions(request)),
|
|
150
|
+
}, nativeOptions(request.providerOptions), request.http?.body);
|
|
151
|
+
if (options.imageInput === "references") {
|
|
152
|
+
const references = yield* Effect.forEach(images, (image) => ProviderShared.mediaReference(image, undefined, route.name));
|
|
153
|
+
return MediaProtocol.json(mergeJsonRecords({
|
|
154
|
+
model: request.model.id,
|
|
155
|
+
prompt: request.prompt,
|
|
156
|
+
input_references: references.length === 0
|
|
157
|
+
? undefined
|
|
158
|
+
: references.map((item) => ({ type: "image_url", image_url: { url: item.value } })),
|
|
159
|
+
}, fields) ?? {});
|
|
160
|
+
}
|
|
161
|
+
// Owned bytes go through multipart edits; remote URLs, file IDs and `json-edits` hosts use the JSON edits body.
|
|
162
|
+
if (options.imageInput === "edits" &&
|
|
163
|
+
images.length > 0 &&
|
|
164
|
+
images.every(isInline) &&
|
|
165
|
+
(mask === undefined || isInline(mask))) {
|
|
86
166
|
const form = new FormData();
|
|
87
167
|
MediaInput.appendFields(form, { model: request.model.id, prompt: request.prompt }, { overlay: fields, reserved: RESERVED_FORM_FIELDS });
|
|
88
168
|
const uploads = yield* Effect.forEach(images, (image) => MediaInput.inlineBytes(route.id, image));
|
|
@@ -91,8 +171,8 @@ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
|
|
|
91
171
|
form.append("mask", MediaInput.blob(yield* MediaInput.inlineBytes(route.id, mask), mask.mediaType), "mask");
|
|
92
172
|
return MediaProtocol.multipart(form);
|
|
93
173
|
}
|
|
94
|
-
const references = yield* Effect.forEach(images, reference);
|
|
95
|
-
const maskReference = mask === undefined ? undefined : yield* reference(mask);
|
|
174
|
+
const references = yield* Effect.forEach(images, (image) => reference(image, request.model.provider));
|
|
175
|
+
const maskReference = mask === undefined ? undefined : yield* reference(mask, request.model.provider);
|
|
96
176
|
return MediaProtocol.json(mergeJsonRecords({
|
|
97
177
|
model: request.model.id,
|
|
98
178
|
prompt: request.prompt,
|
|
@@ -103,21 +183,14 @@ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
|
|
|
103
183
|
// ---------------------------------------------------------------------------
|
|
104
184
|
// 6. Stream parsing
|
|
105
185
|
// ---------------------------------------------------------------------------
|
|
106
|
-
const
|
|
107
|
-
if (body.type === "binary")
|
|
108
|
-
return undefined;
|
|
109
|
-
const value = body.type === "json" ? body.value.output_format : body.value.get("output_format");
|
|
110
|
-
return typeof value === "string" ? value : undefined;
|
|
111
|
-
};
|
|
112
|
-
const usage = (value) => value === undefined
|
|
186
|
+
const usage = (value, provider) => value === undefined
|
|
113
187
|
? undefined
|
|
114
|
-
: {
|
|
115
|
-
type: "tokens",
|
|
188
|
+
: tokenUsage({
|
|
116
189
|
input: value.input_tokens,
|
|
117
190
|
output: value.output_tokens,
|
|
118
191
|
total: value.total_tokens,
|
|
119
|
-
details: {
|
|
120
|
-
};
|
|
192
|
+
details: { [provider]: value },
|
|
193
|
+
});
|
|
121
194
|
/** `size` echoes the rendered `WIDTHxHEIGHT`; `auto` or any other value leaves the dimensions unknown. */
|
|
122
195
|
const info = (format, size) => {
|
|
123
196
|
const match = size?.match(/^(\d+)x(\d+)$/);
|
|
@@ -128,6 +201,15 @@ const eventImage = (frame, label, data, format, size) => MediaInput.decodedAsset
|
|
|
128
201
|
});
|
|
129
202
|
const onEvent = Effect.fnUntraced(function* (state, frame) {
|
|
130
203
|
const event = yield* decodeEvent(frame);
|
|
204
|
+
if (event.type === "unknown")
|
|
205
|
+
return [state, []];
|
|
206
|
+
if (event.type === "error")
|
|
207
|
+
return yield* new AIError({
|
|
208
|
+
reason: classifyProviderFailure({
|
|
209
|
+
message: `${route.name} stream failed: ${event.error?.message ?? "unknown error"}`,
|
|
210
|
+
rawBody: frame,
|
|
211
|
+
}),
|
|
212
|
+
});
|
|
131
213
|
const format = event.output_format;
|
|
132
214
|
if ("partial_image_index" in event) {
|
|
133
215
|
const image = yield* eventImage(frame, `${route.name} partial image`, event.b64_json, format, event.size);
|
|
@@ -141,7 +223,7 @@ const onEvent = Effect.fnUntraced(function* (state, frame) {
|
|
|
141
223
|
size: event.size,
|
|
142
224
|
quality: event.quality,
|
|
143
225
|
background: event.background,
|
|
144
|
-
usage:
|
|
226
|
+
usage: event.usage,
|
|
145
227
|
},
|
|
146
228
|
[ImageOutputEvent.make({ index: state.completed, image })],
|
|
147
229
|
];
|
|
@@ -149,8 +231,10 @@ const onEvent = Effect.fnUntraced(function* (state, frame) {
|
|
|
149
231
|
const onDocument = Effect.fnUntraced(function* (frame) {
|
|
150
232
|
const invalid = (message, cause) => route.frameError(message, frame.document, cause);
|
|
151
233
|
const decoded = yield* decodeDocument(frame.document).pipe(Effect.mapError((cause) => invalid(`${route.name} returned an invalid response`, cause)));
|
|
152
|
-
|
|
153
|
-
const
|
|
234
|
+
// Compatible hosts may omit `output_format` and ignore the requested one, so the bytes decide unreported types.
|
|
235
|
+
const format = decoded.output_format;
|
|
236
|
+
const mediaType = format === undefined ? undefined : `image/${format}`;
|
|
237
|
+
const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.imageOutput(invalid, `${route.name} result ${index}`, item, mediaType, {
|
|
154
238
|
info: info(format, decoded.size),
|
|
155
239
|
}));
|
|
156
240
|
if (images.length === 0)
|
|
@@ -161,19 +245,20 @@ const onDocument = Effect.fnUntraced(function* (frame) {
|
|
|
161
245
|
size: decoded.size,
|
|
162
246
|
quality: decoded.quality,
|
|
163
247
|
background: decoded.background,
|
|
164
|
-
usage:
|
|
248
|
+
usage: decoded.usage,
|
|
165
249
|
};
|
|
166
250
|
return [state, images.map((image, index) => ImageOutputEvent.make({ index, image }))];
|
|
167
251
|
});
|
|
168
252
|
const step = (state, frame) => (typeof frame === "string" ? onEvent(state, frame) : onDocument(frame));
|
|
169
|
-
const finish = (state) => {
|
|
253
|
+
const finish = (state, context) => {
|
|
170
254
|
if (state.completed === 0)
|
|
171
255
|
return Effect.fail(route.incomplete());
|
|
256
|
+
const provider = context.request.model.provider;
|
|
172
257
|
return Effect.succeed([
|
|
173
258
|
ImageFinishEvent.make({
|
|
174
|
-
usage: state.usage,
|
|
259
|
+
usage: usage(state.usage, provider),
|
|
175
260
|
providerMetadata: {
|
|
176
|
-
|
|
261
|
+
[provider]: {
|
|
177
262
|
outputFormat: state.format,
|
|
178
263
|
size: state.size,
|
|
179
264
|
quality: state.quality,
|
|
@@ -186,20 +271,33 @@ const finish = (state) => {
|
|
|
186
271
|
// ---------------------------------------------------------------------------
|
|
187
272
|
// 7. Protocol and route
|
|
188
273
|
// ---------------------------------------------------------------------------
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
body: { from: fromRequest },
|
|
274
|
+
const makeProtocol = (options) => MediaProtocol.stream(route, {
|
|
275
|
+
body: { from: (request) => fromRequest(request, options) },
|
|
192
276
|
frames: (bytes, context) => context.request.mode === "stream"
|
|
193
277
|
? Framing.sse.frame(bytes)
|
|
194
|
-
: Framing.document
|
|
195
|
-
.frame(bytes)
|
|
196
|
-
.pipe(Stream.map((document) => ({ document, requested: requestedFormat(context.body) }))),
|
|
278
|
+
: Framing.document.frame(bytes).pipe(Stream.map((document) => ({ document }))),
|
|
197
279
|
initial: () => ({ completed: 0 }),
|
|
198
280
|
step,
|
|
199
281
|
finish,
|
|
200
282
|
});
|
|
201
|
-
export const
|
|
283
|
+
export const protocol = makeProtocol({ sizing: pixelSize, imageInput: "edits" });
|
|
284
|
+
/**
|
|
285
|
+
* `provider` attributes models, refs, and metadata to an OpenAI-compatible host; it defaults to `openai`. `sizing`
|
|
286
|
+
* replaces the `size` that `aspect` and `resolution` lower to, and `imageInput` how input images are sent.
|
|
287
|
+
*/
|
|
288
|
+
export const model = (input) => {
|
|
289
|
+
const imageInput = input.imageInput ?? "edits";
|
|
290
|
+
const base = input.sizing === undefined && imageInput === "edits"
|
|
291
|
+
? protocol
|
|
292
|
+
: makeProtocol({ sizing: input.sizing ?? pixelSize, imageInput });
|
|
293
|
+
return ImageModel.fromRoute({
|
|
294
|
+
protocol: input.provider === undefined ? base : { ...base, provider: ProviderID.make(input.provider) },
|
|
295
|
+
baseURL: DEFAULT_BASE_URL,
|
|
296
|
+
path: ({ request }) => (imageInput !== "references" && isEdit(request) ? EDIT_PATH : PATH),
|
|
297
|
+
}, input);
|
|
298
|
+
};
|
|
202
299
|
export const OpenAIImages = {
|
|
203
300
|
protocol,
|
|
204
301
|
model,
|
|
302
|
+
pixelSize,
|
|
205
303
|
};
|