UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

308 lines (307 loc) • 12.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { m as readProviderJsonObjectResponse, s as createProviderHttpError } from "./provider-http-errors-Dtgw3x-5.mjs"; import { r as readProviderResponseErrorText } from "./provider-request-header-redaction-Ckk_UIqk.mjs"; import { F as sanitizeAndNormalizeEmbedding, I as debugEmbeddingsLog, N as withRemoteHttpResponse } from "./gateway-startup-plugin-config-DY4atCe0.mjs"; import { A as requireApiKey } from "./model-auth-provider-config-Bnc4upRS.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { n as formatEmbeddingTaskText } from "./embedding-inputs-BGMBVJOW.mjs"; import { r as providerOperationRetryConfig } from "./operation-retry-CNR4uE0x.mjs"; import { n as executeWithApiKeyRotation, t as collectProviderApiKeysForExecution } from "./api-key-rotation-CSR2KXjS.mjs"; import { a as resolveApiKeyForProvider } from "./provider-auth-runtime-DYG2Fn1g.mjs"; import "./provider-http-LcawLneq.mjs"; import { c as resolveEmbeddingProviderSsrFPolicy, i as normalizeEmbeddingModelWithPrefixes, o as embeddingProviderOwnsDestination, s as resolveEmbeddingEndpointUrl } from "./memory-core-host-engine-embeddings-CX_qB4Zn.mjs"; import { n as resolveMemorySecretInputString } from "./secret-input-B3kjG4l-.mjs"; import "./memory-core-host-secret-3cJXCvUc.mjs"; import { t as parseGeminiAuth } from "./gemini-auth-CPHuN1jC.mjs"; import { t as resolveGoogleApiClientHeaders } from "./google-api-client-header-YL-v53wl.mjs"; //#region extensions/google/embedding-provider.ts const DEFAULT_GEMINI_EMBEDDING_MODEL = "gemini-embedding-001"; const DEFAULT_GOOGLE_API_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"; const GEMINI_MAX_INPUT_TOKENS = { "gemini-embedding-001": 2048, "gemini-embedding-2": 8192, "gemini-embedding-2-preview": 8192 }; const GEMINI_EMBEDDING_2_MODELS = /* @__PURE__ */ new Set(["gemini-embedding-2", "gemini-embedding-2-preview"]); const GEMINI_EMBEDDING_2_DEFAULT_DIMENSIONS = 3072; const GOOGLE_RETRY_INFO_TYPE = "type.googleapis.com/google.rpc.RetryInfo"; const GOOGLE_RETRY_DELAY_RE = /^(\d+)(?:\.(\d{1,9}))?s$/u; const GOOGLE_RETRY_INFO_BODY_LIMIT_BYTES = 16384; function malformedGeminiEmbeddingResponse() { return /* @__PURE__ */ new Error("gemini embeddings failed: malformed JSON response"); } function unexpectedGeminiEmbeddingDimensions(e, t) { return /* @__PURE__ */ new Error(`gemini embeddings failed: expected ${e} dimensions, received ${t}`); } /** Direct and downloaded vectors share one invariant before normalization. */ function isValidGeminiEmbeddingValues(e) { return Array.isArray(e) && e.length > 0 && e.every((e) => typeof e === "number" && Number.isFinite(e)); } function readGeminiEmbeddingValues(e) { const t = asOptionalRecord(e)?.values; if (!isValidGeminiEmbeddingValues(t)) throw malformedGeminiEmbeddingResponse(); return t; } function readGeminiBatchEmbeddings(e, t) { if (!Array.isArray(e.embeddings) || e.embeddings.length !== t) throw malformedGeminiEmbeddingResponse(); return e.embeddings.map(readGeminiEmbeddingValues); } function buildGeminiEmbeddingRequest(e) { const t = typeof e.input === "string" ? { text: e.input } : e.input; const n = t.parts?.map((e) => e.type === "text" ? { text: e.text } : { inlineData: { mimeType: e.mimeType, data: e.data } }) ?? [{ text: t.text }]; const r = normalizeGeminiModel(e.model) === "gemini-embedding-2"; const i = { content: { parts: n } }; if (r && !(e.role === "query" ? e.queryInstructionApplied : e.documentFormatApplied) && n.every((e) => "text" in e)) { const t = n[0]; if (t && "text" in t) { const n = e.role === "document" && (e.taskType === "RETRIEVAL_QUERY" || e.taskType === "QUESTION_ANSWERING" || e.taskType === "FACT_VERIFICATION") ? "RETRIEVAL_DOCUMENT" : e.taskType; t.text = formatEmbeddingTaskText(t.text, n); } } else if (!r) i.taskType = e.taskType; if (e.modelPath) i.model = e.modelPath; if (e.outputDimensionality != null) i.outputDimensionality = e.outputDimensionality; return i; } /** Returns true for Gemini Embedding 2 variants with multimodal and extended task support. */ function isGeminiEmbedding2Model(e) { return GEMINI_EMBEDDING_2_MODELS.has(normalizeGeminiModel(e)); } function resolveGeminiOutputDimensionality(e, t) { const n = isGeminiEmbedding2Model(e); if (!n && e !== "gemini-embedding-001") return; if (t == null) return n ? GEMINI_EMBEDDING_2_DEFAULT_DIMENSIONS : void 0; if (!Number.isInteger(t) || t < 128 || t > 3072) throw new Error(`Invalid outputDimensionality ${t} for ${e}. Use an integer between 128 and 3072.`); return t; } function normalizeGeminiModel(e) { return normalizeEmbeddingModelWithPrefixes({ model: e, defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL, prefixes: [ "models/gemini/", "models/google/", "models/", "gemini/", "google/" ] }); } /** * Parses the delay hint from a `google.rpc.RetryInfo` detail inside a Gemini error * body. Callers should prefer a full (bounded) body read over the 500-char * `ProviderHttpError.errorBody` preview: real Gemini 429 payloads run ~1KB+ with * the RetryInfo detail near the end of `error.details`, so the truncated preview * regularly cuts the hint away. */ function extractGoogleRetryInfoDelayMs(e) { if (typeof e !== "string" || !e) return; try { const t = asOptionalRecord(asOptionalRecord(JSON.parse(e))?.error)?.details; if (!Array.isArray(t)) return; let n; for (const e of t) { const t = asOptionalRecord(e); const r = normalizeOptionalString(t?.retryDelay); const i = r ? GOOGLE_RETRY_DELAY_RE.exec(r) : void 0; if (normalizeOptionalString(t?.["@type"]) !== GOOGLE_RETRY_INFO_TYPE || !i) continue; const a = Number(i[1]) * 1e3 + (i[2] ? Math.ceil(Number(`0.${i[2]}`) * 1e3) : 0); if (Number.isSafeInteger(a) && a >= 0) n = Math.max(n ?? a, a); } return n; } catch { return; } } function sanitizeGeminiEmbedding(e, t) { if (t != null && e.length !== t) throw unexpectedGeminiEmbeddingDimensions(t, e.length); return sanitizeAndNormalizeEmbedding(e); } async function fetchGeminiEmbeddingPayload(e) { return await executeWithApiKeyRotation({ provider: "google", apiKeys: e.client.apiKeys, transientRetry: providerOperationRetryConfig("read"), execute: async (t) => { const n = { ...parseGeminiAuth(t).headers, ...e.client.headers }; return await withRemoteHttpResponse({ url: e.endpoint, ssrfPolicy: e.client.ssrfPolicy, signal: e.signal, init: { method: "POST", headers: n, body: JSON.stringify(e.body) }, onResponse: async (t) => { if (!t.ok) { let r; try { r = t.clone(); } catch { r = void 0; } try { const i = await createProviderHttpError(t, "gemini embeddings failed", { requestHeaders: n, signal: e.signal }); let a = i.errorBody; if (r) try { a = await readProviderResponseErrorText(r, GOOGLE_RETRY_INFO_BODY_LIMIT_BYTES, n, e.signal); } catch { e.signal?.throwIfAborted(); a = i.errorBody; } e.signal?.throwIfAborted(); const o = extractGoogleRetryInfoDelayMs(a); if (o !== void 0) i.retryAfterMs = Math.max(o, i.retryAfterMs ?? 0); throw i; } finally { r?.body?.cancel().catch(() => void 0); } } return await readProviderJsonObjectResponse(t, "gemini embeddings failed"); } }); } }); } function normalizeGeminiBaseUrl(e) { const t = e.trim(); if (!t) return DEFAULT_GOOGLE_API_BASE_URL; const n = URL.parse(t); if (!n) return t; n.hash = ""; const r = n.pathname.indexOf("/openai"); n.pathname = (r < 0 ? n.pathname : n.pathname.slice(0, r)).replace(/\/+$/, ""); if (n.origin.toLowerCase() === "https://generativelanguage.googleapis.com" && n.pathname === "/") n.pathname = "/v1beta"; return n.search ? n.href : n.href.replace(/\/$/, ""); } async function createGeminiEmbeddingProvider(e) { const t = await resolveGeminiEmbeddingClient(e); const n = resolveEmbeddingEndpointUrl(t.baseUrl, `${t.modelPath}:embedContent`); const r = resolveEmbeddingEndpointUrl(t.baseUrl, `${t.modelPath}:batchEmbedContents`); const i = t.outputDimensionality; const embedQuery = async (r, a) => { if (!r.trim()) return []; return sanitizeGeminiEmbedding(readGeminiEmbeddingValues((await fetchGeminiEmbeddingPayload({ client: t, endpoint: n, body: buildGeminiEmbeddingRequest({ input: r, model: t.model, role: "query", queryInstructionApplied: a?.queryInstructionApplied, taskType: e.taskType ?? "RETRIEVAL_QUERY", outputDimensionality: i }), signal: a?.signal })).embedding), i); }; const embedDocuments = async (n, a) => { if (n.length === 0) return []; return readGeminiBatchEmbeddings(await fetchGeminiEmbeddingPayload({ client: t, endpoint: r, body: { requests: n.map((n) => buildGeminiEmbeddingRequest({ input: n, model: t.model, role: "document", documentFormatApplied: a?.documentFormatApplied, modelPath: t.modelPath, taskType: e.taskType ?? "RETRIEVAL_DOCUMENT", outputDimensionality: i })) }, signal: a?.signal }), n.length).map((e) => sanitizeGeminiEmbedding(e, i)); }; return { provider: { id: "gemini", model: t.model, maxInputTokens: GEMINI_MAX_INPUT_TOKENS[t.model], embed: async (e, t) => { if (t?.inputType === "query") return await embedQuery(typeof e === "string" ? e : e.text, t); return (await embedDocuments([e], t))[0] ?? []; }, embedBatch: async (e, t) => t?.inputType === "query" ? await Promise.all(e.map((e) => embedQuery(typeof e === "string" ? e : e.text, t))) : await embedDocuments(e, t) }, client: t }; } async function resolveGeminiEmbeddingClient(e) { const t = e.remote; const n = resolveMemorySecretInputString({ value: t?.apiKey, path: "memory.search.remote.apiKey" }); const r = t?.baseUrl?.trim(); const i = e.config.models?.providers?.google; const a = normalizeGeminiBaseUrl(normalizeOptionalString(i?.baseUrl) || DEFAULT_GOOGLE_API_BASE_URL); const o = r || a; const s = normalizeGeminiBaseUrl(o); const c = embeddingProviderOwnsDestination({ baseUrl: s, providerBaseUrl: a }); const l = n ? n : c ? requireApiKey(await resolveApiKeyForProvider({ provider: "google", cfg: e.config, agentDir: e.agentDir }), "google") : void 0; if (!l) throw new Error(`Google embedding credentials are not configured for ${s}. Set memory.search.remote.apiKey for this destination.`); const u = resolveEmbeddingProviderSsrFPolicy({ provider: "google", api: i?.api ?? "google-generative-ai", baseUrl: s, allowPrivateNetwork: i?.request?.allowPrivateNetwork }); const d = {}; for (const [e, n] of [["models.providers.google.headers", c ? i?.headers : void 0], ["memory.search.remote.headers", t?.headers]]) for (const [t, r] of Object.entries(n ?? {})) d[t] = resolveMemorySecretInputString({ value: r ?? null, path: `${e}.${t}` }) ?? ""; const f = { ...d, ...resolveGoogleApiClientHeaders({ baseUrl: s, api: "google-generative-ai", capability: "other", transport: "http" }) }; const p = n ? [l] : collectProviderApiKeysForExecution({ provider: "google", primaryApiKey: l }); const m = normalizeGeminiModel(e.model); const h = m.startsWith("models/") ? m : `models/${m}`; const g = resolveGeminiOutputDimensionality(m, e.dimensions); debugEmbeddingsLog("memory embeddings: gemini client", { rawBaseUrl: o, baseUrl: s, model: m, modelPath: h, outputDimensionality: g, embedEndpoint: resolveEmbeddingEndpointUrl(s, `${h}:embedContent`), batchEndpoint: resolveEmbeddingEndpointUrl(s, `${h}:batchEmbedContents`) }); return { baseUrl: s, headers: f, ssrfPolicy: u, model: m, modelPath: h, apiKeys: p, outputDimensionality: g }; } //#endregion export { isValidGeminiEmbeddingValues as a, isGeminiEmbedding2Model as i, buildGeminiEmbeddingRequest as n, sanitizeGeminiEmbedding as o, createGeminiEmbeddingProvider as r, DEFAULT_GEMINI_EMBEDDING_MODEL as t };