@opencode/ai 2.1.3 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +283 -114
- 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 +13 -22
- package/dist/image-client.js +0 -1
- package/dist/image.d.ts +154 -324
- package/dist/image.js +4 -11
- package/dist/index.d.ts +1426 -34
- package/dist/index.js +127 -24
- package/dist/llm.d.ts +16 -1
- package/dist/llm.js +34 -0
- package/dist/media-client.d.ts +2 -1
- 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 +32 -12
- package/dist/protocols/alibaba-images.d.ts +22 -0
- package/dist/protocols/alibaba-images.js +77 -0
- package/dist/protocols/alibaba-messages.d.ts +62 -27
- package/dist/protocols/alibaba-responses.d.ts +41 -38
- package/dist/protocols/anthropic-messages.d.ts +196 -94
- package/dist/protocols/anthropic-messages.js +47 -16
- package/dist/protocols/bedrock-converse.d.ts +140 -47
- package/dist/protocols/bedrock-converse.js +114 -18
- package/dist/protocols/bedrock-event-stream.js +1 -0
- package/dist/protocols/bfl-images.d.ts +9 -0
- package/dist/protocols/bfl-images.js +17 -15
- package/dist/protocols/cartesia-speech.d.ts +32 -50
- 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/cohere-chat.d.ts +7 -8
- package/dist/protocols/deepgram-speech.d.ts +32 -50
- package/dist/protocols/elevenlabs-speech.d.ts +32 -50
- package/dist/protocols/fal-images.d.ts +10 -1
- package/dist/protocols/fal-images.js +16 -25
- package/dist/protocols/fal-video.js +1 -1
- package/dist/protocols/gemini.d.ts +37 -34
- package/dist/protocols/gemini.js +13 -8
- package/dist/protocols/google-images.d.ts +2 -2
- package/dist/protocols/google-images.js +8 -37
- package/dist/protocols/google-interactions.d.ts +18 -14
- package/dist/protocols/google-interactions.js +14 -7
- package/dist/protocols/google-speech.d.ts +32 -50
- package/dist/protocols/google-speech.js +0 -1
- package/dist/protocols/google-transcription.d.ts +32 -50
- 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 +73 -38
- package/dist/protocols/meta-messages.js +14 -1
- package/dist/protocols/meta-responses.d.ts +84 -78
- package/dist/protocols/meta-responses.js +29 -1
- package/dist/protocols/mistral-chat.d.ts +81 -78
- package/dist/protocols/mistral-chat.js +2 -1
- package/dist/protocols/open-responses-channel.js +47 -46
- package/dist/protocols/open-responses-continuation.d.ts +8 -2
- package/dist/protocols/open-responses-continuation.js +3 -1
- package/dist/protocols/open-responses.d.ts +426 -396
- package/dist/protocols/open-responses.js +16 -25
- package/dist/protocols/openai-chat.d.ts +764 -52
- package/dist/protocols/openai-chat.js +38 -25
- package/dist/protocols/openai-compatible-chat.d.ts +35 -15
- package/dist/protocols/openai-compatible-responses.d.ts +44 -42
- package/dist/protocols/openai-decisions.d.ts +22 -0
- package/dist/protocols/openai-decisions.js +128 -0
- package/dist/protocols/openai-images.d.ts +53 -56
- package/dist/protocols/openai-images.js +100 -34
- package/dist/protocols/openai-responses.d.ts +322 -264
- package/dist/protocols/openai-responses.js +33 -3
- package/dist/protocols/openai-speech.d.ts +32 -50
- package/dist/protocols/openai-speech.js +15 -5
- package/dist/protocols/openai-transcription.d.ts +32 -50
- package/dist/protocols/openai-transcription.js +15 -11
- package/dist/protocols/replicate-images.js +1 -1
- 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/stability-images.d.ts +5 -0
- package/dist/protocols/stability-images.js +4 -9
- 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/partial-json-options.d.ts +0 -1
- package/dist/protocols/utils/partial-json-options.js +0 -1
- 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 +10 -1
- package/dist/protocols/venice-chat.d.ts +71 -53
- package/dist/protocols/venice-chat.js +7 -6
- package/dist/protocols/xai-images.d.ts +1 -2
- package/dist/protocols/xai-images.js +9 -2
- package/dist/protocols/xai-responses.d.ts +88 -78
- package/dist/protocols/xai-responses.js +28 -2
- package/dist/protocols/xai-video.d.ts +1 -1
- package/dist/protocols/xai-video.js +11 -8
- package/dist/protocols/zai-chat.d.ts +54 -30
- package/dist/protocols/zai-chat.js +8 -3
- package/dist/protocols/zai-images.d.ts +3 -1
- package/dist/protocols/zai-images.js +12 -11
- package/dist/protocols/zai-messages.d.ts +72 -35
- package/dist/protocols/zai-messages.js +3 -2
- package/dist/provider-error.js +24 -7
- package/dist/providers/alibaba/images.d.ts +2 -0
- package/dist/providers/alibaba/images.js +1 -0
- package/dist/providers/alibaba.d.ts +146 -85
- package/dist/providers/alibaba.js +16 -8
- package/dist/providers/amazon-bedrock-mantle.d.ts +277 -218
- package/dist/providers/amazon-bedrock.d.ts +48 -28
- package/dist/providers/amazon-bedrock.js +11 -11
- package/dist/providers/anthropic-compatible.d.ts +64 -29
- package/dist/providers/anthropic.d.ts +64 -29
- package/dist/providers/azure/images.d.ts +2 -0
- package/dist/providers/azure/images.js +1 -0
- package/dist/providers/azure.d.ts +156 -115
- 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 +75 -25
- package/dist/providers/baseten.js +41 -8
- package/dist/providers/cerebras.d.ts +66 -24
- 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 +409 -272
- package/dist/providers/cloudflare-ai-gateway.js +33 -6
- 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 +79 -25
- package/dist/providers/cloudflare-workers-ai.js +45 -9
- package/dist/providers/cohere.d.ts +117 -75
- package/dist/providers/deepinfra.d.ts +66 -24
- package/dist/providers/deepseek.d.ts +66 -24
- 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.d.ts +108 -37
- package/dist/providers/digitalocean.js +39 -8
- package/dist/providers/fireworks.d.ts +66 -24
- package/dist/providers/google/images.d.ts +2 -0
- package/dist/providers/google/images.js +1 -0
- 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 +33 -12
- package/dist/providers/google-vertex-messages.d.ts +64 -29
- package/dist/providers/google-vertex-mistral.d.ts +17 -17
- package/dist/providers/google-vertex-responses.d.ts +38 -35
- package/dist/providers/google-vertex.d.ts +20 -18
- package/dist/providers/google-vertex.js +32 -15
- package/dist/providers/google.d.ts +22 -21
- package/dist/providers/google.js +15 -8
- package/dist/providers/groq.d.ts +66 -28
- package/dist/providers/groq.js +0 -6
- package/dist/providers/meta.d.ts +144 -85
- package/dist/providers/minimax.d.ts +145 -86
- package/dist/providers/mistral.d.ts +28 -28
- package/dist/providers/moonshot.d.ts +277 -218
- package/dist/providers/open-responses-options.d.ts +0 -1
- package/dist/providers/open-responses-options.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 +38 -35
- package/dist/providers/openai-compatible.d.ts +36 -13
- package/dist/providers/openai-compatible.js +22 -10
- package/dist/providers/openai-options.d.ts +3 -2
- package/dist/providers/openai-options.js +0 -1
- package/dist/providers/openai.d.ts +146 -109
- package/dist/providers/openai.js +20 -4
- package/dist/providers/opencode/decisions.d.ts +2 -0
- package/dist/providers/opencode/decisions.js +1 -0
- package/dist/providers/opencode.d.ts +9 -10
- 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.d.ts +128 -47
- package/dist/providers/openrouter.js +38 -16
- package/dist/providers/togetherai.d.ts +66 -24
- 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 +9 -10
- package/dist/providers/typesafe-ai.js +10 -8
- package/dist/providers/venice.d.ts +214 -20
- 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 +10 -16
- package/dist/providers/vercel-ai-gateway.js +31 -85
- package/dist/providers/xai/images.d.ts +2 -0
- package/dist/providers/xai/images.js +1 -0
- package/dist/providers/xai.d.ts +40 -17
- 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.d.ts +224 -85
- package/dist/providers/zai.d.ts +110 -23
- package/dist/providers/zai.js +15 -8
- package/dist/route/auth-options.d.ts +0 -3
- package/dist/route/auth.d.ts +0 -2
- package/dist/route/auth.js +0 -2
- package/dist/route/client.d.ts +2 -4
- package/dist/route/client.js +29 -8
- package/dist/route/decision.d.ts +58 -0
- package/dist/route/decision.js +75 -0
- package/dist/route/executor-service.js +1 -1
- 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 +1 -0
- package/dist/route/media-protocol.js +12 -8
- package/dist/route/media.d.ts +5 -1
- package/dist/route/media.js +6 -2
- 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 +6 -2
- package/dist/schema/messages.js +3 -0
- package/dist/schema/options.d.ts +5 -3
- package/dist/schema/options.js +8 -3
- package/dist/speech-client.d.ts +13 -22
- package/dist/speech-client.js +0 -1
- package/dist/speech.d.ts +148 -283
- package/dist/speech.js +2 -4
- package/dist/testing.d.ts +25 -24
- package/dist/testing.js +3 -21
- package/dist/transcription-client.d.ts +13 -22
- package/dist/transcription.d.ts +148 -283
- package/dist/transcription.js +1 -1
- package/dist/utils/media-type.js +22 -1
- package/dist/video-client.d.ts +13 -22
- package/dist/video-client.js +0 -1
- package/dist/video.d.ts +115 -250
- package/dist/video.js +3 -5
- package/package.json +516 -13
- 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 -115
- 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/provider.d.ts +0 -23
- package/dist/provider.js +0 -2
|
@@ -0,0 +1,101 @@
|
|
|
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
|
+
/** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
|
|
8
|
+
type MediaInput = NonNullable<DecisionModelCompatibility["mediaInput"]> | "state.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 cost: Schema.optional<Schema.Number>;
|
|
29
|
+
}>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
|
|
30
|
+
readonly id: Schema.optional<Schema.String>;
|
|
31
|
+
readonly provider: Schema.optional<Schema.String>;
|
|
32
|
+
readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
|
|
33
|
+
}>;
|
|
34
|
+
export type Response = Schema.Schema.Type<typeof Response>;
|
|
35
|
+
/** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
|
|
36
|
+
export declare const encodeBody: (request: DecisionRequestFor, fallback: MediaInput) => Effect.Effect<{
|
|
37
|
+
questions: any;
|
|
38
|
+
state: unknown;
|
|
39
|
+
assets?: undefined;
|
|
40
|
+
} | {
|
|
41
|
+
questions: any;
|
|
42
|
+
state: readonly unknown[];
|
|
43
|
+
assets: {
|
|
44
|
+
[k: string]: {
|
|
45
|
+
type: string;
|
|
46
|
+
format: string;
|
|
47
|
+
data_base64: string;
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
}, AIError, never>;
|
|
51
|
+
/** Map System One's answers, keyed by question name, back to the request's question order. */
|
|
52
|
+
export declare const toResponse: (data: Response, request: DecisionRequestFor, providerMetadataKey: string, invalid: (message: string) => AIError) => Effect.Effect<never, AIError, never> | Effect.Effect<DecisionResponse, never, never>;
|
|
53
|
+
export declare const protocol: DecisionRoute.Protocol;
|
|
54
|
+
/** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
|
|
55
|
+
export declare const route: DecisionRoute.Route;
|
|
56
|
+
export declare const SystemOne: {
|
|
57
|
+
readonly Response: Schema.Struct<{
|
|
58
|
+
readonly model: Schema.String;
|
|
59
|
+
readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
|
|
60
|
+
readonly type: Schema.Literal<"noul">;
|
|
61
|
+
readonly noul: Schema.Number;
|
|
62
|
+
}>, Schema.Struct<{
|
|
63
|
+
readonly type: Schema.Literal<"choice">;
|
|
64
|
+
readonly choice: Schema.String;
|
|
65
|
+
readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
|
|
66
|
+
readonly confidence: Schema.Number;
|
|
67
|
+
}>, Schema.Struct<{
|
|
68
|
+
readonly type: Schema.Literal<"score">;
|
|
69
|
+
readonly score: Schema.Number;
|
|
70
|
+
readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
|
|
71
|
+
readonly confidence: Schema.Number;
|
|
72
|
+
}>]>>;
|
|
73
|
+
readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
|
|
74
|
+
readonly input_tokens: Schema.optional<Schema.Number>;
|
|
75
|
+
readonly output_tokens: Schema.optional<Schema.Number>;
|
|
76
|
+
readonly cost: Schema.optional<Schema.Number>;
|
|
77
|
+
}>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
|
|
78
|
+
readonly id: Schema.optional<Schema.String>;
|
|
79
|
+
readonly provider: Schema.optional<Schema.String>;
|
|
80
|
+
readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
|
|
81
|
+
}>;
|
|
82
|
+
readonly encodeBody: (request: DecisionRequestFor, fallback: MediaInput) => Effect.Effect<{
|
|
83
|
+
questions: any;
|
|
84
|
+
state: unknown;
|
|
85
|
+
assets?: undefined;
|
|
86
|
+
} | {
|
|
87
|
+
questions: any;
|
|
88
|
+
state: readonly unknown[];
|
|
89
|
+
assets: {
|
|
90
|
+
[k: string]: {
|
|
91
|
+
type: string;
|
|
92
|
+
format: string;
|
|
93
|
+
data_base64: string;
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
}, AIError, never>;
|
|
97
|
+
readonly toResponse: typeof toResponse;
|
|
98
|
+
readonly protocol: DecisionRoute.Protocol;
|
|
99
|
+
readonly route: DecisionRoute.Route;
|
|
100
|
+
};
|
|
101
|
+
export {};
|
|
@@ -0,0 +1,230 @@
|
|
|
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 { 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
|
+
cost: Schema.optional(Schema.Number),
|
|
31
|
+
}), [JsonObject]);
|
|
32
|
+
export const Response = Schema.Struct({
|
|
33
|
+
model: Schema.String,
|
|
34
|
+
answers: Schema.Record(Schema.String, Answer),
|
|
35
|
+
usage: Schema.optional(NativeUsage),
|
|
36
|
+
id: Schema.optional(Schema.String),
|
|
37
|
+
provider: Schema.optional(Schema.String),
|
|
38
|
+
provider_metadata: Schema.optional(Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown))),
|
|
39
|
+
});
|
|
40
|
+
const ID = "system-one";
|
|
41
|
+
const NAME = "System One";
|
|
42
|
+
/** The System One body without `model`; media goes where the model's `mediaInput` says, else `fallback`. */
|
|
43
|
+
export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (request, fallback) {
|
|
44
|
+
const questions = yield* encodeQuestions(request.questions);
|
|
45
|
+
const placed = yield* placeMedia(request, request.model.compatibility?.mediaInput ?? fallback);
|
|
46
|
+
return { ...mergeJsonRecords(request.providerOptions, request.http?.body), ...placed, questions };
|
|
47
|
+
});
|
|
48
|
+
const encodeQuestions = (questions) => Effect.forEach(questions, (question) => {
|
|
49
|
+
if (question.type === "predicate")
|
|
50
|
+
return Effect.succeed([question.name, { type: "noul", instructions: question.instructions }]);
|
|
51
|
+
if (question.type === "score")
|
|
52
|
+
return Effect.succeed([
|
|
53
|
+
question.name,
|
|
54
|
+
{
|
|
55
|
+
type: "score",
|
|
56
|
+
instructions: question.instructions,
|
|
57
|
+
criteria: question.levels.map((level) => level.description === undefined ? level.label : `${level.label}: ${level.description}`),
|
|
58
|
+
},
|
|
59
|
+
]);
|
|
60
|
+
// Options are map keys, so `true` is sent as "true" and mapped back by `choiceValue`.
|
|
61
|
+
const keys = question.choices.map((choice) => String(choice.value));
|
|
62
|
+
if (new Set(keys).size !== keys.length)
|
|
63
|
+
return Effect.fail(ProviderShared.invalidRequest(`System One choice options are strings; "${question.name}" has a boolean and a string with the same text`));
|
|
64
|
+
return Effect.succeed([
|
|
65
|
+
question.name,
|
|
66
|
+
{
|
|
67
|
+
type: "choice",
|
|
68
|
+
instructions: question.instructions,
|
|
69
|
+
criteria: Object.fromEntries(question.choices.map((choice) => [String(choice.value), choice.description ?? null])),
|
|
70
|
+
},
|
|
71
|
+
]);
|
|
72
|
+
}).pipe(Effect.map(Object.fromEntries));
|
|
73
|
+
const placeMedia = Effect.fnUntraced(function* (request, mediaInput) {
|
|
74
|
+
const parts = request.input;
|
|
75
|
+
const unsupported = (asset, accepted) => new AIError({
|
|
76
|
+
reason: new UnsupportedOperationError({
|
|
77
|
+
operation: "decision.media",
|
|
78
|
+
provider: request.model.provider,
|
|
79
|
+
route: request.model.route.id,
|
|
80
|
+
message: `${NAME} takes ${accepted} here; got ${asset.mediaType}`,
|
|
81
|
+
}),
|
|
82
|
+
});
|
|
83
|
+
const media = parts.flatMap((part) => (part.type === "media" ? [part.media] : []));
|
|
84
|
+
if (media.length === 0)
|
|
85
|
+
return { state: state(parts.map(plain)) };
|
|
86
|
+
if (mediaInput === "state")
|
|
87
|
+
return { state: yield* Effect.forEach(parts, (part) => stateItem(part, unsupported)) };
|
|
88
|
+
// Chat-style content in one user message: text and JSON as text parts, media as in `state`.
|
|
89
|
+
if (mediaInput === "state.messages")
|
|
90
|
+
return {
|
|
91
|
+
state: {
|
|
92
|
+
messages: [
|
|
93
|
+
{
|
|
94
|
+
role: "user",
|
|
95
|
+
content: yield* Effect.forEach(parts, (part) => part.type === "media"
|
|
96
|
+
? stateItem(part, unsupported)
|
|
97
|
+
: Effect.succeed({ type: "text", text: part.type === "text" ? part.text : encodeJson(part.value) })),
|
|
98
|
+
},
|
|
99
|
+
],
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
if (mediaInput === "root") {
|
|
103
|
+
const lists = { image: "images", audio: "audio", video: "videos" };
|
|
104
|
+
const unplaced = media.find((asset) => !Object.hasOwn(lists, asset.kind));
|
|
105
|
+
if (unplaced !== undefined)
|
|
106
|
+
return yield* unsupported(unplaced, "images, audio and video");
|
|
107
|
+
const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
|
|
108
|
+
const fields = Object.fromEntries(Object.entries(lists).flatMap(([kind, field]) => {
|
|
109
|
+
const items = inline.filter((_, index) => media[index].kind === kind).map((item) => item.dataUrl);
|
|
110
|
+
return items.length === 0 ? [] : [[field, items]];
|
|
111
|
+
}));
|
|
112
|
+
return { state: state(parts.filter((part) => part.type !== "media").map(plain)), ...fields };
|
|
113
|
+
}
|
|
114
|
+
const unplaced = media.find((asset) => asset.kind !== "image");
|
|
115
|
+
if (unplaced !== undefined)
|
|
116
|
+
return yield* unsupported(unplaced, "images");
|
|
117
|
+
const inline = yield* Effect.forEach(media, (asset) => ProviderShared.requireInlineMedia(NAME, asset));
|
|
118
|
+
// Every occurrence of a reference string in the body is replaced with its image, so it must not be ordinary text.
|
|
119
|
+
const reference = (index) => `<image-${index + 1}>`;
|
|
120
|
+
const items = parts.reduce((acc, part) => part.type === "media"
|
|
121
|
+
? { next: acc.next + 1, values: [...acc.values, reference(acc.next)] }
|
|
122
|
+
: { next: acc.next, values: [...acc.values, plain(part)] }, { next: 0, values: [] }).values;
|
|
123
|
+
return {
|
|
124
|
+
state: items,
|
|
125
|
+
assets: Object.fromEntries(inline.map((item, index) => [
|
|
126
|
+
reference(index),
|
|
127
|
+
{ type: "image", format: item.mime.slice("image/".length), data_base64: item.base64 },
|
|
128
|
+
])),
|
|
129
|
+
};
|
|
130
|
+
});
|
|
131
|
+
/** A lone text or JSON part is the state itself; several are a list. */
|
|
132
|
+
const state = (items) => (items.length === 1 ? items[0] : items);
|
|
133
|
+
const plain = (part) => {
|
|
134
|
+
if (part.type === "text")
|
|
135
|
+
return part.text;
|
|
136
|
+
if (part.type === "json")
|
|
137
|
+
return part.value;
|
|
138
|
+
return undefined;
|
|
139
|
+
};
|
|
140
|
+
const stateItem = (part, unsupported) => {
|
|
141
|
+
if (part.type !== "media")
|
|
142
|
+
return Effect.succeed(plain(part));
|
|
143
|
+
const asset = part.media;
|
|
144
|
+
if (asset.kind !== "image" && asset.kind !== "audio" && asset.kind !== "video")
|
|
145
|
+
return Effect.fail(unsupported(asset, "images, audio and video"));
|
|
146
|
+
return ProviderShared.requireInlineMedia(NAME, asset).pipe(Effect.map((inline) => {
|
|
147
|
+
if (asset.kind === "image")
|
|
148
|
+
return { type: "image_url", image_url: { url: inline.dataUrl } };
|
|
149
|
+
if (asset.kind === "video")
|
|
150
|
+
return { type: "video_url", video_url: { url: inline.dataUrl } };
|
|
151
|
+
return { type: "input_audio", input_audio: { data: inline.base64, format: inline.mime.slice("audio/".length) } };
|
|
152
|
+
}));
|
|
153
|
+
};
|
|
154
|
+
/** Map System One's answers, keyed by question name, back to the request's question order. */
|
|
155
|
+
export const toResponse = (data, request, providerMetadataKey, invalid) => {
|
|
156
|
+
const names = request.questions.map((question) => question.name);
|
|
157
|
+
if (Object.keys(data.answers).length !== names.length || !names.every((name) => Object.hasOwn(data.answers, name)))
|
|
158
|
+
return Effect.fail(invalid("System One answers do not match the requested questions"));
|
|
159
|
+
return Effect.succeed(new DecisionResponse({
|
|
160
|
+
answers: request.questions.map((question) => toAnswer(question, data.answers[question.name])),
|
|
161
|
+
usage: data.usage === undefined
|
|
162
|
+
? undefined
|
|
163
|
+
: new DecisionUsage({
|
|
164
|
+
inputTokens: data.usage.input_tokens,
|
|
165
|
+
outputTokens: data.usage.output_tokens,
|
|
166
|
+
totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
|
|
167
|
+
cost: data.usage.cost,
|
|
168
|
+
}),
|
|
169
|
+
providerMetadata: {
|
|
170
|
+
[providerMetadataKey]: {
|
|
171
|
+
model: data.model,
|
|
172
|
+
...(data.usage === undefined ? {} : { usage: data.usage }),
|
|
173
|
+
...(data.id === undefined ? {} : { responseId: data.id }),
|
|
174
|
+
...(data.provider === undefined ? {} : { provider: data.provider }),
|
|
175
|
+
...data.provider_metadata?.[providerMetadataKey],
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
}));
|
|
179
|
+
};
|
|
180
|
+
const toAnswer = (question, answer) => {
|
|
181
|
+
if (answer.type === "noul")
|
|
182
|
+
return { name: question.name, type: "predicate", probability: answer.noul };
|
|
183
|
+
if (answer.type === "choice") {
|
|
184
|
+
const choices = question.type === "choice" ? question.choices : [];
|
|
185
|
+
const value = (key) => choices.find((choice) => String(choice.value) === key)?.value ?? key;
|
|
186
|
+
const rank = (key) => {
|
|
187
|
+
const index = choices.findIndex((choice) => String(choice.value) === key);
|
|
188
|
+
return index === -1 ? choices.length : index;
|
|
189
|
+
};
|
|
190
|
+
return {
|
|
191
|
+
name: question.name,
|
|
192
|
+
type: "choice",
|
|
193
|
+
choice: value(answer.choice),
|
|
194
|
+
probabilities: Object.entries(answer.probabilities)
|
|
195
|
+
.toSorted(([a], [b]) => rank(a) - rank(b))
|
|
196
|
+
.map(([key, probability]) => ({ value: value(key), probability })),
|
|
197
|
+
confidence: answer.confidence,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
const levels = question.type === "score" ? question.levels : [];
|
|
201
|
+
return {
|
|
202
|
+
name: question.name,
|
|
203
|
+
type: "score",
|
|
204
|
+
score: answer.score,
|
|
205
|
+
probabilities: Object.entries(answer.probabilities)
|
|
206
|
+
.map(([key, probability]) => ({ value: Number(key), label: levels[Number(key)]?.label ?? key, probability }))
|
|
207
|
+
.toSorted((a, b) => a.value - b.value),
|
|
208
|
+
confidence: answer.confidence,
|
|
209
|
+
};
|
|
210
|
+
};
|
|
211
|
+
const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "typesafe-ai" }).decodeJson(Response);
|
|
212
|
+
export const protocol = DecisionRoute.protocol({
|
|
213
|
+
id: ID,
|
|
214
|
+
name: NAME,
|
|
215
|
+
inlineMedia: true,
|
|
216
|
+
body: {
|
|
217
|
+
from: (request) => encodeBody(request, "assets").pipe(Effect.map((body) => ({ ...body, model: request.model.id }))),
|
|
218
|
+
},
|
|
219
|
+
response: {
|
|
220
|
+
decode: (response, context) => decodeDocument(response).pipe(Effect.flatMap((output) => toResponse(output.value, context.request, context.providerMetadataKey, output.invalid))),
|
|
221
|
+
},
|
|
222
|
+
});
|
|
223
|
+
/** TypeSafe's API, the reference System One host; other hosts change the endpoint and auth with `route.with(...)`. */
|
|
224
|
+
export const route = DecisionRoute.make({
|
|
225
|
+
id: ID,
|
|
226
|
+
provider: "typesafe-ai",
|
|
227
|
+
protocol,
|
|
228
|
+
endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }),
|
|
229
|
+
});
|
|
230
|
+
export const SystemOne = { Response, encodeBody, toResponse, protocol, route };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
-
import type
|
|
2
|
+
import { type CacheHint, type LLMRequest } from "../../schema/index.js";
|
|
3
3
|
export declare const CachePointBlock: Schema.Struct<{
|
|
4
4
|
readonly cachePoint: Schema.Struct<{
|
|
5
5
|
readonly type: Schema.tag<"default">;
|
|
6
|
-
readonly ttl: Schema.optional<Schema.Literals<readonly ["
|
|
6
|
+
readonly ttl: Schema.optional<Schema.TemplateLiteral<readonly [Schema.Number, Schema.Literals<readonly ["ms", "s", "m", "h", "d"]>]>>;
|
|
7
7
|
}>;
|
|
8
8
|
}>;
|
|
9
9
|
export type CachePointBlock = Schema.Schema.Type<typeof CachePointBlock>;
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
-
import {
|
|
2
|
+
import { CacheTTL } from "../../schema/index.js";
|
|
3
|
+
import { newBreakpoints } from "./cache.js";
|
|
3
4
|
// Bedrock cache markers are positional: emit a `cachePoint` block immediately
|
|
4
5
|
// after the content the caller wants treated as a cacheable prefix. Bedrock
|
|
5
|
-
// accepts optional `ttl
|
|
6
|
+
// accepts an optional `ttl` such as "5m" or "1h" on cachePoint.
|
|
6
7
|
export const CachePointBlock = Schema.Struct({
|
|
7
8
|
cachePoint: Schema.Struct({
|
|
8
9
|
type: Schema.tag("default"),
|
|
9
|
-
ttl: Schema.optional(
|
|
10
|
+
ttl: Schema.optional(CacheTTL),
|
|
10
11
|
}),
|
|
11
12
|
});
|
|
12
13
|
const LEGACY_CLAUDE = ["anthropic.claude-instant", "anthropic.claude-v1", "anthropic.claude-v2", "anthropic.claude-3-"];
|
|
@@ -34,8 +35,6 @@ export const breakpoints = (model) => {
|
|
|
34
35
|
ttl1h: !short,
|
|
35
36
|
};
|
|
36
37
|
};
|
|
37
|
-
const DEFAULT_5M = { cachePoint: { type: "default" } };
|
|
38
|
-
const DEFAULT_1H = { cachePoint: { type: "default", ttl: "1h" } };
|
|
39
38
|
export const block = (breakpoints, cache) => {
|
|
40
39
|
if (!breakpoints.supported)
|
|
41
40
|
return undefined;
|
|
@@ -46,6 +45,8 @@ export const block = (breakpoints, cache) => {
|
|
|
46
45
|
return undefined;
|
|
47
46
|
}
|
|
48
47
|
breakpoints.remaining -= 1;
|
|
49
|
-
|
|
48
|
+
// Older Claude releases cache for five minutes only, so a one-hour request falls back to the default.
|
|
49
|
+
const ttl = cache.ttl === "1h" && !breakpoints.ttl1h ? undefined : cache.ttl;
|
|
50
|
+
return { cachePoint: { type: "default", ...(ttl === undefined ? {} : { ttl }) } };
|
|
50
51
|
};
|
|
51
52
|
export * as BedrockCache from "./bedrock-cache.js";
|
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
import type { CacheHint } from "../../schema/index.js";
|
|
1
|
+
import type { CacheHint, CacheTTL } from "../../schema/index.js";
|
|
2
2
|
export interface Breakpoints {
|
|
3
3
|
remaining: number;
|
|
4
4
|
dropped: number;
|
|
5
5
|
}
|
|
6
6
|
export declare const newBreakpoints: (cap: number) => Breakpoints;
|
|
7
|
-
export declare const ttlBucket: (ttlSeconds: number | undefined) => "1h" | undefined;
|
|
8
7
|
export declare const cacheControl: () => (cache: CacheHint | undefined) => {
|
|
9
8
|
type: "ephemeral";
|
|
10
|
-
ttl:
|
|
9
|
+
ttl: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
|
|
11
10
|
} | undefined;
|
|
11
|
+
export declare const openAIRequestTTL: (ttl: CacheTTL | undefined) => {
|
|
12
|
+
prompt_cache_retention?: undefined;
|
|
13
|
+
prompt_cache_options?: undefined;
|
|
14
|
+
} | {
|
|
15
|
+
prompt_cache_retention: string;
|
|
16
|
+
prompt_cache_options?: undefined;
|
|
17
|
+
} | {
|
|
18
|
+
prompt_cache_retention?: undefined;
|
|
19
|
+
prompt_cache_options: {
|
|
20
|
+
ttl: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s`;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
export const newBreakpoints = (cap) => ({ remaining: cap, dropped: 0 });
|
|
2
|
-
// Requests of at least one hour use the explicit `"1h"` bucket; shorter
|
|
3
|
-
// requests omit the wire TTL and use the provider default.
|
|
4
|
-
export const ttlBucket = (ttlSeconds) => ttlSeconds !== undefined && ttlSeconds >= 3600 ? "1h" : undefined;
|
|
5
2
|
export const cacheControl = () => {
|
|
6
3
|
const breakpoints = newBreakpoints(4);
|
|
7
4
|
return (cache) => {
|
|
8
5
|
if (cache === undefined || breakpoints.remaining === 0)
|
|
9
6
|
return undefined;
|
|
10
7
|
breakpoints.remaining -= 1;
|
|
11
|
-
return { type: "ephemeral", ttl:
|
|
8
|
+
return { type: "ephemeral", ttl: cache.ttl };
|
|
12
9
|
};
|
|
13
10
|
};
|
|
11
|
+
// OpenAI's request-level lifetime. `prompt_cache_retention` takes only "24h" (or "in_memory") and is the only
|
|
12
|
+
// control before GPT-5.6; every other lifetime goes to `prompt_cache_options.ttl`, which GPT-5.6+, Kimi and
|
|
13
|
+
// DeepInfra read.
|
|
14
|
+
export const openAIRequestTTL = (ttl) => {
|
|
15
|
+
if (ttl === undefined)
|
|
16
|
+
return {};
|
|
17
|
+
if (ttl === "24h")
|
|
18
|
+
return { prompt_cache_retention: ttl };
|
|
19
|
+
return { prompt_cache_options: { ttl } };
|
|
20
|
+
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Effect, Schema, type Stream } from "effect";
|
|
2
|
-
import type {
|
|
2
|
+
import type { Tool } from "@opencode/schema/tool";
|
|
3
|
+
import { Media } from "../../media.js";
|
|
3
4
|
import type { MediaProtocol } from "../../route/media-protocol.js";
|
|
4
5
|
import { AIError, type MediaUsage, type ProviderMetadata } from "../../schema/index.js";
|
|
5
6
|
declare const UsageMetadata: Schema.Struct<{
|
|
@@ -51,12 +52,11 @@ export declare const blocked: (name: string, chunk: Chunk, frame: string) => AIE
|
|
|
51
52
|
export declare const contentFiltered: (finishReason: string | undefined) => boolean;
|
|
52
53
|
/** Callers check that the response produced no output: a policy stop after output is a partial result instead. */
|
|
53
54
|
export declare const withheld: (name: string, chunk: Chunk, frame: string) => AIError | undefined;
|
|
54
|
-
/** Any finish reason other than `STOP` means the output may be cut short, so it is surfaced rather than dropped. */
|
|
55
|
-
export declare const notices: (name: string, state: Metadata) => ReadonlyArray<Media.Notice> | undefined;
|
|
56
55
|
export declare const usage: (usage: UsageMetadata | undefined) => MediaUsage | undefined;
|
|
57
56
|
export declare const providerMetadata: (state: Metadata) => ProviderMetadata;
|
|
58
57
|
export declare const path: (model: string, mode: MediaProtocol.Mode) => string;
|
|
59
58
|
export declare const frames: (bytes: Stream.Stream<Uint8Array, AIError>, mode: MediaProtocol.Mode) => Stream.Stream<string, AIError, never>;
|
|
59
|
+
export declare const toolMedia: (item: Tool.FileContent) => Media.Asset;
|
|
60
60
|
export declare const mediaPart: (route: string, asset: Media.Asset) => Effect.Effect<{
|
|
61
61
|
readonly fileData: {
|
|
62
62
|
readonly mimeType: string;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
|
+
import { Media } from "../../media.js";
|
|
2
3
|
import { Framing } from "../../route/framing.js";
|
|
3
|
-
import { AIError, ContentPolicyError, ProviderID } from "../../schema/index.js";
|
|
4
|
+
import { AIError, ContentPolicyError, ProviderID, tokenUsage, } from "../../schema/index.js";
|
|
4
5
|
import { ProviderShared } from "../shared.js";
|
|
5
6
|
import { MediaInput } from "./media-input.js";
|
|
6
7
|
const PROVIDER = ProviderID.make("google");
|
|
@@ -63,34 +64,27 @@ export const withheld = (name, chunk, frame) => {
|
|
|
63
64
|
reason: new ContentPolicyError({ message: `${name} withheld its output (${finishReason})`, body: frame }),
|
|
64
65
|
});
|
|
65
66
|
};
|
|
66
|
-
/** Any finish reason other than `STOP` means the output may be cut short, so it is surfaced rather than dropped. */
|
|
67
|
-
export const notices = (name, state) => state.finishReason === undefined || state.finishReason === "STOP"
|
|
68
|
-
? undefined
|
|
69
|
-
: [
|
|
70
|
-
{
|
|
71
|
-
type: contentFiltered(state.finishReason) ? "filtered" : "other",
|
|
72
|
-
message: `${name} finished with ${state.finishReason}`,
|
|
73
|
-
providerMetadata: { google: { finishReason: state.finishReason } },
|
|
74
|
-
},
|
|
75
|
-
];
|
|
76
67
|
export const usage = (usage) => usage === undefined
|
|
77
68
|
? undefined
|
|
78
|
-
: {
|
|
79
|
-
type: "tokens",
|
|
69
|
+
: tokenUsage({
|
|
80
70
|
input: usage.promptTokenCount,
|
|
81
71
|
output: usage.candidatesTokenCount,
|
|
82
72
|
total: ProviderShared.totalTokens(usage.promptTokenCount, usage.candidatesTokenCount, usage.totalTokenCount),
|
|
83
73
|
details: { google: usage },
|
|
84
|
-
};
|
|
74
|
+
});
|
|
85
75
|
export const providerMetadata = (state) => ({
|
|
86
76
|
google: { finishReason: state.finishReason, modelVersion: state.modelVersion, responseId: state.responseId },
|
|
87
77
|
});
|
|
88
78
|
export const path = (model, mode) => mode === "stream" ? `/models/${model}:streamGenerateContent?alt=sse` : `/models/${model}:generateContent`;
|
|
89
79
|
// `generateContent` answers with one document shaped exactly like a streamed chunk, so it is a single frame.
|
|
90
80
|
export const frames = (bytes, mode) => mode === "stream" ? Framing.sse.frame(bytes) : Framing.document.frame(bytes);
|
|
91
|
-
|
|
81
|
+
export const toolMedia = (item) => item.mime.startsWith("video/") && item.uri.startsWith("gs://")
|
|
82
|
+
? Media.ref(PROVIDER, item.uri, item.mime)
|
|
83
|
+
: ProviderShared.toolFileMedia(item).media;
|
|
92
84
|
export const mediaPart = (route, asset) => {
|
|
93
|
-
const fileUri =
|
|
85
|
+
const fileUri = asset.kind === "video" && asset.source.type === "url" && /^https?:\/\//i.test(asset.source.url)
|
|
86
|
+
? asset.source.url
|
|
87
|
+
: MediaInput.refID(asset, PROVIDER);
|
|
94
88
|
if (fileUri !== undefined)
|
|
95
89
|
return Effect.succeed({ fileData: { mimeType: asset.mediaType, fileUri } });
|
|
96
90
|
return ProviderShared.requireInlineMedia(route, asset).pipe(Effect.map((media) => ({ inlineData: { mimeType: media.mime, data: media.base64 } })));
|
|
@@ -1,3 +1,8 @@
|
|
|
1
1
|
import type { JsonSchema } from "../../schema/index.js";
|
|
2
|
+
export declare const SCHEMA_MAPS: Set<string>;
|
|
3
|
+
export declare const VALUES: Set<string>;
|
|
4
|
+
export declare const mapValues: (record: Record<string, unknown>, map: (value: unknown, key: string) => unknown) => {
|
|
5
|
+
[k: string]: unknown;
|
|
6
|
+
};
|
|
2
7
|
export declare const normalize: (schema: JsonSchema) => JsonSchema;
|
|
3
8
|
export * as GeminiJsonSchema from "./gemini-json-schema.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isRecord } from "../../utils/record.js";
|
|
2
2
|
// Gemini's `parametersJsonSchema` accepts standard JSON Schema, but rejects a few shapes that
|
|
3
3
|
// published tool schemas commonly contain. Rewrite only those and send everything else unchanged.
|
|
4
|
-
const SCHEMA_MAPS = new Set([
|
|
4
|
+
export const SCHEMA_MAPS = new Set([
|
|
5
5
|
"properties",
|
|
6
6
|
"patternProperties",
|
|
7
7
|
"$defs",
|
|
@@ -9,8 +9,8 @@ const SCHEMA_MAPS = new Set([
|
|
|
9
9
|
"dependentSchemas",
|
|
10
10
|
"dependencies",
|
|
11
11
|
]);
|
|
12
|
-
const VALUES = new Set(["const", "default", "enum", "examples", "dependentRequired"]);
|
|
13
|
-
const mapValues = (record, map) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value, key)]));
|
|
12
|
+
export const VALUES = new Set(["const", "default", "enum", "examples", "dependentRequired"]);
|
|
13
|
+
export const mapValues = (record, map) => Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value, key)]));
|
|
14
14
|
const normalizeNode = (schema) => {
|
|
15
15
|
if (Array.isArray(schema))
|
|
16
16
|
return schema.map(normalizeNode);
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { MediaProtocol } from "../../route/media-protocol.js";
|
|
3
|
+
export interface Size {
|
|
4
|
+
readonly width: number;
|
|
5
|
+
readonly height: number;
|
|
6
|
+
}
|
|
7
|
+
/** The shared `aspect` and `resolution` fields of an image request. */
|
|
8
|
+
export interface Shape {
|
|
9
|
+
readonly aspect?: string;
|
|
10
|
+
readonly resolution?: string;
|
|
11
|
+
}
|
|
12
|
+
/** What a provider accepts for free width and height. */
|
|
13
|
+
export interface Limits {
|
|
14
|
+
readonly multiple: number;
|
|
15
|
+
readonly minEdge?: number;
|
|
16
|
+
readonly maxEdge?: number;
|
|
17
|
+
readonly minPixels?: number;
|
|
18
|
+
readonly maxPixels?: number;
|
|
19
|
+
/** Long edge over short edge. */
|
|
20
|
+
readonly maxRatio?: number;
|
|
21
|
+
}
|
|
22
|
+
export declare const isRequested: (shape: Shape) => boolean;
|
|
23
|
+
/** `1K` is 1, `2K` is 2, `0.5K` is 0.5; anything else is not a tier. */
|
|
24
|
+
export declare const tier: (resolution: string) => number | undefined;
|
|
25
|
+
/** Free width and height: the tier sets the pixel count (`1K` is about 1024²), the aspect sets the proportions. */
|
|
26
|
+
export declare const fit: (shape: Shape, limits: Limits) => Size;
|
|
27
|
+
/** The listed size closest to the shape: nearest aspect ratio first, then nearest pixel count. */
|
|
28
|
+
export declare const nearest: (shape: Shape, sizes: ReadonlyArray<Size>) => Size;
|
|
29
|
+
/** Free width and height that must honor the shape; a size that misses it fails. */
|
|
30
|
+
export declare const exact: (route: MediaProtocol.Identity, shape: Shape, limits: Limits) => Effect.Effect<undefined, never, never> | Effect.Effect<never, import("../../effect.js").AIError, never> | Effect.Effect<Size, never, never>;
|
|
31
|
+
export * as ImageSizing from "./image-sizing.js";
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
export const isRequested = (shape) => shape.aspect !== undefined || shape.resolution !== undefined;
|
|
3
|
+
/** `1K` is 1, `2K` is 2, `0.5K` is 0.5; anything else is not a tier. */
|
|
4
|
+
export const tier = (resolution) => {
|
|
5
|
+
const match = /^(\d+(?:\.\d+)?)k$/i.exec(resolution);
|
|
6
|
+
return match === null ? undefined : Number(match[1]);
|
|
7
|
+
};
|
|
8
|
+
/** Free width and height: the tier sets the pixel count (`1K` is about 1024²), the aspect sets the proportions. */
|
|
9
|
+
export const fit = (shape, limits) => {
|
|
10
|
+
const maxRatio = limits.maxRatio ?? Infinity;
|
|
11
|
+
const ratio = Math.min(maxRatio, Math.max(1 / maxRatio, aspectRatio(shape)));
|
|
12
|
+
const area = targetPixels(shape);
|
|
13
|
+
const width = Math.sqrt(area * ratio);
|
|
14
|
+
const height = Math.sqrt(area / ratio);
|
|
15
|
+
const up = Math.max((limits.minEdge ?? 0) / Math.min(width, height), Math.sqrt((limits.minPixels ?? 0) / area));
|
|
16
|
+
const scaled = Math.max(1, up);
|
|
17
|
+
const down = Math.min((limits.maxEdge ?? Infinity) / (Math.max(width, height) * scaled), Math.sqrt((limits.maxPixels ?? Infinity) / area) / scaled);
|
|
18
|
+
// Round away from a limit the size reached, including one it lands on exactly, so it never crosses it.
|
|
19
|
+
const round = down <= 1 ? Math.floor : up >= 1 ? Math.ceil : Math.round;
|
|
20
|
+
const snap = (edge) => Math.max(limits.multiple, round(Number(((edge * scaled * Math.min(1, down)) / limits.multiple).toFixed(6))) * limits.multiple);
|
|
21
|
+
return { width: snap(width), height: snap(height) };
|
|
22
|
+
};
|
|
23
|
+
/** The listed size closest to the shape: nearest aspect ratio first, then nearest pixel count. */
|
|
24
|
+
export const nearest = (shape, sizes) => {
|
|
25
|
+
const ratio = Math.log(aspectRatio(shape));
|
|
26
|
+
const area = Math.log(targetPixels(shape));
|
|
27
|
+
const distance = (size) => [
|
|
28
|
+
Math.abs(Math.log(size.width / size.height) - ratio),
|
|
29
|
+
Math.abs(Math.log(size.width * size.height) - area),
|
|
30
|
+
];
|
|
31
|
+
return sizes.reduce((best, size) => {
|
|
32
|
+
const [sizeRatio, sizeArea] = distance(size);
|
|
33
|
+
const [bestRatio, bestArea] = distance(best);
|
|
34
|
+
if (Math.abs(sizeRatio - bestRatio) > 1e-9)
|
|
35
|
+
return sizeRatio < bestRatio ? size : best;
|
|
36
|
+
return sizeArea < bestArea ? size : best;
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
/** Free width and height that must honor the shape; a size that misses it fails. */
|
|
40
|
+
export const exact = (route, shape, limits) => {
|
|
41
|
+
if (!isRequested(shape))
|
|
42
|
+
return Effect.succeed(undefined);
|
|
43
|
+
const size = fit(shape, limits);
|
|
44
|
+
const requested = missed(shape, size);
|
|
45
|
+
if (requested === undefined)
|
|
46
|
+
return Effect.succeed(size);
|
|
47
|
+
return Effect.fail(route.unsupported(shape.resolution === undefined ? "media.aspect" : "media.resolution", `${route.name} can't render ${requested}; the closest size it takes is ${describe(size)}. Change aspect or resolution, or set the size in providerOptions`));
|
|
48
|
+
};
|
|
49
|
+
/** A size more than 2% off the requested aspect or more than √2 per edge off the requested tier. */
|
|
50
|
+
const missed = (shape, size) => {
|
|
51
|
+
const aspectMissed = shape.aspect !== undefined && Math.abs(Math.log(size.width / size.height / aspectRatio(shape))) > 0.02;
|
|
52
|
+
const requestedTier = shape.resolution === undefined ? undefined : tier(shape.resolution);
|
|
53
|
+
const resolutionMissed = shape.resolution !== undefined &&
|
|
54
|
+
(requestedTier === undefined ||
|
|
55
|
+
Math.abs(Math.log2(Math.sqrt(size.width * size.height) / (requestedTier * 1024))) > 0.5);
|
|
56
|
+
if (!aspectMissed && !resolutionMissed)
|
|
57
|
+
return undefined;
|
|
58
|
+
return [shape.aspect, shape.resolution].filter((value) => value !== undefined).join(" at ");
|
|
59
|
+
};
|
|
60
|
+
const aspectRatio = (shape) => {
|
|
61
|
+
const [width, height] = (shape.aspect ?? "1:1").split(":").map(Number);
|
|
62
|
+
return width / height;
|
|
63
|
+
};
|
|
64
|
+
const targetPixels = (shape) => ((tier(shape.resolution ?? "1K") ?? 1) * 1024) ** 2;
|
|
65
|
+
const describe = (size) => {
|
|
66
|
+
const divisor = gcd(size.width, size.height);
|
|
67
|
+
const width = size.width / divisor;
|
|
68
|
+
const height = size.height / divisor;
|
|
69
|
+
const ratio = width <= 32 && height <= 32 ? `${width}:${height}` : `${(size.width / size.height).toFixed(2)}:1`;
|
|
70
|
+
return `${size.width}x${size.height} (${ratio})`;
|
|
71
|
+
};
|
|
72
|
+
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
|
|
73
|
+
export * as ImageSizing from "./image-sizing.js";
|