GeezerVison is showing github.com — feat(ai): add Google Decisions (#63369) · drpr/opencode@0bd8cee
File treeExpand file treeCollapse file tree Open diff view settings fixtures/recordings/google-decision
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/ai/package.json +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 77 | 77 | "./providers/google-vertex/messages": "./src/providers/google-vertex/messages.ts", | 78 | 78 | "./providers/google-vertex/mistral": "./src/providers/google-vertex/mistral.ts", | 79 | 79 | "./providers/google-vertex/responses": "./src/providers/google-vertex/responses.ts", | | 80 | + "./providers/google/decisions": "./src/providers/google/decisions.ts", | 80 | 81 | "./providers/google/embeddings": "./src/providers/google/embeddings.ts", | 81 | 82 | "./providers/google/images": "./src/providers/google/images.ts", | 82 | 83 | "./providers/google/interactions": "./src/providers/google/interactions.ts", | | 141 | 142 | "./protocols/cloudflare-run-decisions": "./src/protocols/cloudflare-run-decisions.ts", | 142 | 143 | "./protocols/cloudflare-workers-ai-images": "./src/protocols/cloudflare-workers-ai-images.ts", | 143 | 144 | "./protocols/deepgram-transcription": "./src/protocols/deepgram-transcription.ts", | | 145 | + "./protocols/google-decisions": "./src/protocols/google-decisions.ts", | 144 | 146 | "./protocols/google-images": "./src/protocols/google-images.ts", | 145 | 147 | "./protocols/google-speech": "./src/protocols/google-speech.ts", | 146 | 148 | "./protocols/google-transcription": "./src/protocols/google-transcription.ts", | |
Collapse file Copy file name to clipboard +179Lines changed: 179 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +import { Effect, Schema } from "effect" | | 2 | +import { DecisionResponse, DecisionUsage, type DecisionPart, type DecisionRequest } from "../decision.js" | | 3 | +import type { Media } from "../media.js" | | 4 | +import { DecisionRoute } from "../route/decision.js" | | 5 | +import { Endpoint } from "../route/endpoint.js" | | 6 | +import { MediaProtocol } from "../route/media-protocol.js" | | 7 | +import { | | 8 | + AIError, | | 9 | + ProviderID, | | 10 | + UnsupportedOperationError, | | 11 | + mergeJsonRecords, | | 12 | + type ProviderOptions, | | 13 | +} from "../schema/index.js" | | 14 | +import { encodeJson } from "../utils/json.js" | | 15 | +import { JsonObject, knownString, ProviderShared } from "./shared.js" | | 16 | +import { SystemOne } from "./system-one.js" | | 17 | +import { MediaInput } from "./utils/media-input.js" | | 18 | + | | 19 | +const ID = "google-decisions" | | 20 | +const NAME = "Google Decisions" | | 21 | +export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta" | | 22 | + | | 23 | +const Options = Schema.Struct({ | | 24 | + /** Token budget for every image and video input; `ultra_high` applies to images only. */ | | 25 | + mediaResolution: Schema.optional(knownString<"low" | "medium" | "high" | "ultra_high">()), | | 26 | +}) | | 27 | +/** Known fields map to their wire names; anything else is sent as given. */ | | 28 | +export type OptionsInput = ProviderOptions & typeof Options.Encoded | | 29 | + | | 30 | +const Usage = Schema.StructWithRest( | | 31 | + Schema.Struct({ | | 32 | + total_input_tokens: Schema.optional(Schema.Number), | | 33 | + total_output_tokens: Schema.optional(Schema.Number), | | 34 | + total_tokens: Schema.optional(Schema.Number), | | 35 | + }), | | 36 | + [JsonObject], | | 37 | +) | | 38 | +const Response = Schema.Struct({ | | 39 | + answers: Schema.Record(Schema.String, SystemOne.Answer), | | 40 | + usage: Schema.optional(Usage), | | 41 | +}) | | 42 | + | | 43 | +const decodeOptions = ProviderShared.validateWith(Schema.decodeUnknownEffect(Options)) | | 44 | + | | 45 | +const fromRequest = Effect.fn("GoogleDecisions.fromRequest")(function* (request: DecisionRequest) { | | 46 | + const options = yield* decodeOptions(request.providerOptions ?? {}) | | 47 | + const { mediaResolution: _, ...native } = request.providerOptions ?? {} | | 48 | + return { | | 49 | + ...mergeJsonRecords(native, request.http?.body), | | 50 | + model: request.model.id, | | 51 | + input: separateText( | | 52 | + yield* Effect.forEach(request.input, (part) => inputPart(request, part, options.mediaResolution)), | | 53 | + ), | | 54 | + questions: { | | 55 | + ...(yield* SystemOne.encodeQuestions(request.questions)), | | 56 | + // Google names System One's predicate criteria `true_description` and `false_description`. | | 57 | + ...Object.fromEntries( | | 58 | + request.questions.flatMap((question) => | | 59 | + question.type === "predicate" && question.criteria !== undefined | | 60 | + ? [ | | 61 | + [ | | 62 | + question.name, | | 63 | + { | | 64 | + type: "noul", | | 65 | + instructions: question.instructions, | | 66 | + criteria: { | | 67 | + ...(question.criteria.true === undefined ? {} : { true_description: question.criteria.true }), | | 68 | + ...(question.criteria.false === undefined ? {} : { false_description: question.criteria.false }), | | 69 | + }, | | 70 | + }, | | 71 | + ], | | 72 | + ] | | 73 | + : [], | | 74 | + ), | | 75 | + ), | | 76 | + }, | | 77 | + } | | 78 | +}) | | 79 | + | | 80 | +const inputPart = ( | | 81 | + request: DecisionRequest, | | 82 | + part: DecisionPart, | | 83 | + resolution: string | undefined, | | 84 | +): Effect.Effect<Record<string, unknown>, AIError> => { | | 85 | + if (part.type === "text") return Effect.succeed({ type: "text", text: part.text }) | | 86 | + // Google reads every text block as text; JSON is serialized so its keys are never parsed as content blocks. | | 87 | + if (part.type === "json") return Effect.succeed({ type: "text", text: encodeJson(part.value) }) | | 88 | + return mediaPart(request, part.media, resolution) | | 89 | +} | | 90 | + | | 91 | +// Google joins adjacent text blocks with no separator, so each one after another starts on a new line. | | 92 | +const separateText = (blocks: ReadonlyArray<Record<string, unknown>>) => | | 93 | + blocks.map((block, index) => | | 94 | + block.type === "text" && blocks[index - 1]?.type === "text" ? { ...block, text: `\n${block.text}` } : block, | | 95 | + ) | | 96 | + | | 97 | +const mediaPart = (request: DecisionRequest, asset: Media.Asset, resolution: string | undefined) => { | | 98 | + const type = | | 99 | + asset.kind === "image" || asset.kind === "audio" || asset.kind === "video" | | 100 | + ? asset.kind | | 101 | + : asset.mediaType.toLowerCase() === "application/pdf" | | 102 | + ? "document" | | 103 | + : undefined | | 104 | + if (type === undefined) | | 105 | + return Effect.fail( | | 106 | + new AIError({ | | 107 | + reason: new UnsupportedOperationError({ | | 108 | + operation: "decision.media", | | 109 | + provider: request.model.provider, | | 110 | + route: request.model.route.id, | | 111 | + message: `${NAME} takes images, audio, video and PDFs; got ${asset.mediaType}`, | | 112 | + }), | | 113 | + }), | | 114 | + ) | | 115 | + const block = { | | 116 | + type, | | 117 | + mime_type: asset.mediaType.toLowerCase(), | | 118 | + // `ultra_high` is image-only, so video keeps Google's default for it. | | 119 | + ...(resolution !== undefined && (type === "image" || (type === "video" && resolution !== "ultra_high")) | | 120 | + ? { resolution } | | 121 | + : {}), | | 122 | + } | | 123 | + const inline = asset.inline() | | 124 | + if (inline) return Effect.succeed({ ...block, data: inline.base64 }) | | 125 | + // Google fetches URLs itself, so one that needs our download credentials can't be forwarded. | | 126 | + if (asset.source.type === "url" && /^https:\/\//i.test(asset.source.url) && asset.headers === undefined) | | 127 | + return Effect.succeed({ ...block, uri: asset.source.url }) | | 128 | + const file = MediaInput.refID(asset, ProviderID.make("google")) | | 129 | + if (file !== undefined) return Effect.succeed({ ...block, uri: file }) | | 130 | + return Effect.fail( | | 131 | + ProviderShared.invalidRequest( | | 132 | + `${NAME} accepts inline media, public HTTPS URLs and Google Files API URIs; materialize ${asset.source.type} media first`, | | 133 | + ), | | 134 | + ) | | 135 | +} | | 136 | + | | 137 | +const decodeDocument = MediaProtocol.identity({ id: ID, name: NAME, provider: "google" }).decodeJson(Response) | | 138 | + | | 139 | +export const protocol = DecisionRoute.protocol({ | | 140 | + id: ID, | | 141 | + name: NAME, | | 142 | + body: { from: fromRequest }, | | 143 | + response: { | | 144 | + decode: Effect.fn("GoogleDecisions.decodeResponse")(function* (response, context) { | | 145 | + const output = yield* decodeDocument(response) | | 146 | + const data = output.value | | 147 | + const answers = data.answers | | 148 | + const names = context.request.questions.map((question) => question.name) | | 149 | + if (Object.keys(answers).length !== names.length || !names.every((name) => Object.hasOwn(answers, name))) | | 150 | + return yield* output.invalid(`${NAME} answers do not match the requested questions`) | | 151 | + return new DecisionResponse({ | | 152 | + answers: context.request.questions.map((question) => SystemOne.toAnswer(question, answers[question.name])), | | 153 | + usage: | | 154 | + data.usage === undefined | | 155 | + ? undefined | | 156 | + : new DecisionUsage({ | | 157 | + inputTokens: data.usage.total_input_tokens, | | 158 | + outputTokens: data.usage.total_output_tokens, | | 159 | + totalTokens: ProviderShared.totalTokens( | | 160 | + data.usage.total_input_tokens, | | 161 | + data.usage.total_output_tokens, | | 162 | + data.usage.total_tokens, | | 163 | + ), | | 164 | + }), | | 165 | + providerMetadata: | | 166 | + data.usage === undefined ? undefined : { [context.providerMetadataKey]: { usage: data.usage } }, | | 167 | + }) | | 168 | + }), | | 169 | + }, | | 170 | +}) | | 171 | + | | 172 | +export const route = DecisionRoute.make({ | | 173 | + id: ID, | | 174 | + provider: "google", | | 175 | + protocol, | | 176 | + endpoint: Endpoint.path("/decisions", { baseURL: DEFAULT_BASE_URL }), | | 177 | +}) | | 178 | + | | 179 | +export * as GoogleDecisions from "./google-decisions.js" |
Collapse file Copy file name to clipboardExpand all lines: packages/ai/src/protocols/index.ts +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -3,6 +3,7 @@ export * as BedrockConverse from "./bedrock-converse.js" | 3 | 3 | export * as CloudflareRunDecisions from "./cloudflare-run-decisions.js" | 4 | 4 | export * as CohereChat from "./cohere-chat.js" | 5 | 5 | export * as Gemini from "./gemini.js" | | 6 | +export * as GoogleDecisions from "./google-decisions.js" | 6 | 7 | export * as GoogleEmbedContent from "./google-embed-content.js" | 7 | 8 | export * as GoogleInteractions from "./google-interactions.js" | 8 | 9 | export * as GoogleVertexPredictEmbeddings from "./google-vertex-predict-embeddings.js" | |
Collapse file Copy file name to clipboardExpand all lines: packages/ai/src/protocols/system-one.ts +11-2Lines changed: 11 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -94,7 +94,7 @@ const encodeQuestions = (questions: ReadonlyArray<DecisionQuestion>) => | 94 | 94 | if (new Set(keys).size !== keys.length) | 95 | 95 | return Effect.fail( | 96 | 96 | ProviderShared.invalidRequest( | 97 | | - `System One choice options are strings; "${question.name}" has a boolean and a string with the same text`, | | 97 | + `Decision choice options are sent as string keys; "${question.name}" has a boolean and a string with the same text`, | 98 | 98 | ), | 99 | 99 | ) | 100 | 100 | return Effect.succeed([ | @@ -294,4 +294,13 @@ export const route = DecisionRoute.make({ | 294 | 294 | endpoint: Endpoint.path("/systemone", { baseURL: DEFAULT_BASE_URL }), | 295 | 295 | }) | 296 | 296 |
| 297 | | -export const SystemOne = { Response, encodeBody, toResponse, protocol, route } as const | | 297 | +export const SystemOne = { | | 298 | + Answer, | | 299 | + Response, | | 300 | + encodeBody, | | 301 | + encodeQuestions, | | 302 | + toAnswer, | | 303 | + toResponse, | | 304 | + protocol, | | 305 | + route, | | 306 | +} as const |
Collapse file Copy file name to clipboardExpand all lines: packages/ai/src/provider-error.ts +6Lines changed: 6 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -131,6 +131,12 @@ const CONTENT_POLICY_CODES = new Set([ | 131 | 131 | "refusal", | 132 | 132 | "datainspectionfailed", | 133 | 133 | "moderation_blocked", | | 134 | + // Gemini Decisions rejects blocked input with these `error.code` strings on a 400. | | 135 | + "safety", | | 136 | + "prohibited_content", | | 137 | + "blocklist", | | 138 | + "image_safety", | | 139 | + "content_blocked", | 134 | 140 | ]) | 135 | 141 | // OpenCode Zen replaces upstream codes outside its allow-list but keeps the original | 136 | 142 | // as a `[code]` label at the start of the rewritten message. | |
Collapse file Copy file name to clipboardExpand all lines: packages/ai/src/providers/google.ts +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 8 | 8 | GoogleEmbedContent, | 9 | 9 | type OptionsInput as GoogleEmbeddingOptionsInput, | 10 | 10 | } from "../protocols/google-embed-content.js" | | 11 | +import { GoogleDecisions } from "../protocols/google-decisions.js" | 11 | 12 | import { GoogleInteractions } from "../protocols/google-interactions.js" | 12 | 13 | import { GoogleImages } from "../protocols/google-images.js" | 13 | 14 | import { GoogleSpeech } from "../protocols/google-speech.js" | @@ -23,6 +24,7 @@ export type { GoogleVideoOptions } from "../protocols/google-video.js" | 23 | 24 | export type GeminiOptionsInput = Gemini.OptionsInput | 24 | 25 | export type GeminiProviderOptionsInput = Gemini.ProviderOptionsInput | 25 | 26 | export type GoogleInteractionsOptionsInput = GoogleInteractions.OptionsInput | | 27 | +export type GoogleDecisionsOptionsInput = GoogleDecisions.OptionsInput | 26 | 28 |
| 27 | 29 | export const id = ProviderID.make("google") | 28 | 30 |
| @@ -77,6 +79,10 @@ export const configure = (input: Config = {}) => { | 77 | 79 | transcription: (modelID: string | ModelID) => GoogleTranscription.model({ ...media, id: modelID }), | 78 | 80 | embedding: (modelID: string | ModelID, providerOptions?: ProviderOptions) => | 79 | 81 | embeddingRoute.model<GoogleEmbeddingOptionsInput>({ id: modelID, providerOptions }), | | 82 | + decision: (modelID: string | ModelID, providerOptions?: ProviderOptions) => | | 83 | + GoogleDecisions.route | | 84 | + .with({ endpoint: { baseURL: media.baseURL }, auth: media.auth, headers: media.headers, http: media.http }) | | 85 | + .model<GoogleDecisions.OptionsInput>({ id: modelID, providerOptions }), | 80 | 86 | configure, | 81 | 87 | } | 82 | 88 | } | @@ -92,6 +98,10 @@ export const embeddingModel = (modelID: string, settings?: Settings) => { | 92 | 98 | const input = toConfig(settings) | 93 | 99 | return configure(input).embedding(modelID, input.providerOptions) | 94 | 100 | } | | 101 | +export const decisionModel = (modelID: string, settings?: Settings) => { | | 102 | + const input = toConfig(settings) | | 103 | + return configure(input).decision(modelID, input.providerOptions) | | 104 | +} | 95 | 105 |
| 96 | 106 | export const image = provider.image | 97 | 107 | export const embedding = provider.embedding | @@ -100,3 +110,4 @@ export const interactions = provider.interactions | 100 | 110 | export const video = provider.video | 101 | 111 | export const speech = provider.speech | 102 | 112 | export const transcription = provider.transcription | | 113 | +export const decision = provider.decision |
Collapse file Copy file name to clipboard +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +export { decisionModel as model } from "../google.js" | | 2 | +export type { Settings } from "../google.js" |
|