|
| 1 | +import { Effect, Schema } from "effect" |
| 2 | +import { EmbeddingResponse, EmbeddingUsage, type EmbeddingRequest } from "../embedding.js" |
| 3 | +import { EmbeddingRoute } from "../route/embedding.js" |
| 4 | +import { Endpoint } from "../route/endpoint.js" |
| 5 | +import { MediaProtocol } from "../route/media-protocol.js" |
| 6 | +import { mergeJsonRecords, type AIError, type OpenString } from "../schema/index.js" |
| 7 | +import { GeminiGenerateContent } from "./utils/gemini-generate-content.js" |
| 8 | + |
| 9 | +const ID = "google-embed-content" |
| 10 | +const NAME = "Google embedContent" |
| 11 | +export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta" |
| 12 | +/** `batchEmbedContents` takes at most 100 requests. */ |
| 13 | +export const MAX_BATCH = 100 |
| 14 | + |
| 15 | +export type TaskType = OpenString< |
| 16 | + | "RETRIEVAL_QUERY" |
| 17 | + | "RETRIEVAL_DOCUMENT" |
| 18 | + | "SEMANTIC_SIMILARITY" |
| 19 | + | "CLASSIFICATION" |
| 20 | + | "CLUSTERING" |
| 21 | + | "QUESTION_ANSWERING" |
| 22 | + | "FACT_VERIFICATION" |
| 23 | + | "CODE_RETRIEVAL_QUERY" |
| 24 | +> |
| 25 | + |
| 26 | +/** |
| 27 | + * Per-value embedding fields, sent with each value. `taskType` replaces the one `inputType` maps to; Gemini Embedding 2 |
| 28 | + * ignores task types and documents task prefixes in the text instead (`task: search result | query: …`). |
| 29 | + */ |
| 30 | +export interface OptionsInput { |
| 31 | + readonly [key: string]: unknown |
| 32 | + readonly taskType?: TaskType |
| 33 | + readonly title?: string |
| 34 | +} |
| 35 | + |
| 36 | +/** Vertex `embedContentConfig` fields; Vertex alone takes `autoTruncate`, `documentOcr` and `audioTrackExtraction`. */ |
| 37 | +export interface VertexOptionsInput extends OptionsInput { |
| 38 | + readonly autoTruncate?: boolean |
| 39 | + readonly documentOcr?: boolean |
| 40 | + readonly audioTrackExtraction?: boolean |
| 41 | +} |
| 42 | + |
| 43 | +const Values = Schema.Struct({ values: Schema.Array(Schema.Number) }) |
| 44 | + |
| 45 | +const UsageMetadata = Schema.StructWithRest(Schema.Struct({ promptTokenCount: Schema.optional(Schema.Number) }), [ |
| 46 | + Schema.Record(Schema.String, Schema.Unknown), |
| 47 | +]) |
| 48 | + |
| 49 | +const BatchResponse = Schema.Struct({ |
| 50 | + embeddings: Schema.Array(Values), |
| 51 | + usageMetadata: Schema.optional(UsageMetadata), |
| 52 | +}) |
| 53 | + |
| 54 | +const SingleResponse = Schema.Struct({ |
| 55 | + embedding: Values, |
| 56 | + usageMetadata: Schema.optional(UsageMetadata), |
| 57 | + truncated: Schema.optional(Schema.Boolean), |
| 58 | +}) |
| 59 | + |
| 60 | +const TASK_TYPES = { query: "RETRIEVAL_QUERY", document: "RETRIEVAL_DOCUMENT" } as const |
| 61 | + |
| 62 | +// Each value is its own content: several parts in one content embed into one aggregated vector. |
| 63 | +const content = (value: EmbeddingRequest["values"][number]): Effect.Effect<{ readonly parts: [unknown] }, AIError> => |
| 64 | + typeof value === "string" |
| 65 | + ? Effect.succeed({ parts: [{ text: value }] }) |
| 66 | + : GeminiGenerateContent.mediaPart(NAME, value).pipe(Effect.map((part) => ({ parts: [part] }))) |
| 67 | + |
| 68 | +const config = (request: EmbeddingRequest) => ({ |
| 69 | + ...(request.inputType === undefined ? {} : { taskType: TASK_TYPES[request.inputType] }), |
| 70 | + ...(request.dimensions === undefined ? {} : { outputDimensionality: request.dimensions }), |
| 71 | + ...request.providerOptions, |
| 72 | +}) |
| 73 | + |
| 74 | +const identity = MediaProtocol.identity({ id: ID, name: NAME, provider: "google" }) |
| 75 | +const decodeBatch = identity.decodeJson(BatchResponse) |
| 76 | +const decodeSingle = identity.decodeJson(SingleResponse) |
| 77 | + |
| 78 | +const usage = (metadata: Schema.Schema.Type<typeof UsageMetadata> | undefined) => |
| 79 | + metadata?.promptTokenCount === undefined ? undefined : new EmbeddingUsage({ inputTokens: metadata.promptTokenCount }) |
| 80 | + |
| 81 | +/** Gemini API `batchEmbedContents`: one request per value, so every value gets its own vector. */ |
| 82 | +export const protocol = EmbeddingRoute.protocol({ |
| 83 | + id: ID, |
| 84 | + name: NAME, |
| 85 | + body: { |
| 86 | + from: Effect.fn("GoogleEmbedContent.fromRequest")(function* (request: EmbeddingRequest) { |
| 87 | + const contents = yield* Effect.forEach(request.values, content) |
| 88 | + const fields = config(request) |
| 89 | + return ( |
| 90 | + mergeJsonRecords( |
| 91 | + { requests: contents.map((item) => ({ model: `models/${request.model.id}`, content: item, ...fields })) }, |
| 92 | + request.http?.body, |
| 93 | + ) ?? {} |
| 94 | + ) |
| 95 | + }), |
| 96 | + }, |
| 97 | + response: { |
| 98 | + decode: Effect.fn("GoogleEmbedContent.decodeResponse")(function* (response, context) { |
| 99 | + const output = yield* decodeBatch(response) |
| 100 | + return new EmbeddingResponse({ |
| 101 | + embeddings: output.value.embeddings.map((item) => item.values), |
| 102 | + usage: usage(output.value.usageMetadata), |
| 103 | + providerMetadata: { |
| 104 | + [context.providerMetadataKey]: |
| 105 | + output.value.usageMetadata === undefined ? {} : { usageMetadata: output.value.usageMetadata }, |
| 106 | + }, |
| 107 | + }) |
| 108 | + }), |
| 109 | + }, |
| 110 | +}) |
| 111 | + |
| 112 | +/** |
| 113 | + * Vertex `embedContent`: one content per request, with options under `embedContentConfig`. Routes using it set |
| 114 | + * `maxValues: 1`. |
| 115 | + */ |
| 116 | +export const vertexProtocol = EmbeddingRoute.protocol({ |
| 117 | + id: "google-vertex-embed-content", |
| 118 | + name: "Google Vertex embedContent", |
| 119 | + body: { |
| 120 | + from: Effect.fn("GoogleEmbedContent.vertexFromRequest")(function* (request: EmbeddingRequest) { |
| 121 | + const contents = yield* Effect.forEach(request.values, content) |
| 122 | + const fields = config(request) |
| 123 | + return ( |
| 124 | + mergeJsonRecords( |
| 125 | + { |
| 126 | + content: contents[0], |
| 127 | + ...(Object.keys(fields).length === 0 ? {} : { embedContentConfig: fields }), |
| 128 | + }, |
| 129 | + request.http?.body, |
| 130 | + ) ?? {} |
| 131 | + ) |
| 132 | + }), |
| 133 | + }, |
| 134 | + response: { |
| 135 | + decode: Effect.fn("GoogleEmbedContent.vertexDecodeResponse")(function* (response, context) { |
| 136 | + const output = yield* decodeSingle(response) |
| 137 | + return new EmbeddingResponse({ |
| 138 | + embeddings: [output.value.embedding.values], |
| 139 | + usage: usage(output.value.usageMetadata), |
| 140 | + providerMetadata: { |
| 141 | + [context.providerMetadataKey]: { |
| 142 | + ...(output.value.usageMetadata === undefined ? {} : { usageMetadata: output.value.usageMetadata }), |
| 143 | + ...(output.value.truncated === undefined ? {} : { truncated: output.value.truncated }), |
| 144 | + }, |
| 145 | + }, |
| 146 | + }) |
| 147 | + }), |
| 148 | + }, |
| 149 | +}) |
| 150 | + |
| 151 | +export const route = EmbeddingRoute.make({ |
| 152 | + id: ID, |
| 153 | + provider: "google", |
| 154 | + protocol, |
| 155 | + endpoint: Endpoint.path(({ request }) => `/models/${request.model.id}:batchEmbedContents`, { |
| 156 | + baseURL: DEFAULT_BASE_URL, |
| 157 | + }), |
| 158 | + maxValues: MAX_BATCH, |
| 159 | +}) |
| 160 | + |
| 161 | +export const GoogleEmbedContent = { |
| 162 | + protocol, |
| 163 | + vertexProtocol, |
| 164 | + route, |
| 165 | +} as const |
0 commit comments