openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
236 lines (235 loc) • 9.19 kB
JavaScript
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { m as readProviderJsonObjectResponse, r as assertOkOrThrowProviderError, s as createProviderHttpError } from "./provider-http-errors-Dtgw3x-5.mjs";
import { I as debugEmbeddingsLog, N as withRemoteHttpResponse } from "./gateway-startup-plugin-config-DY4atCe0.mjs";
import { _ as resolveProviderOperationTimeoutMs, r as createProviderOperationDeadline, v as waitProviderOperationPollInterval } from "./shared-CfcMLHIP.mjs";
import "./provider-http-LcawLneq.mjs";
import { b as formatBatchErrorDetail, d as runEmbeddingBatchGroups, g as readEmbeddingBatchJsonl, p as buildBatchHeaders, s as resolveEmbeddingEndpointUrl, u as buildEmbeddingBatchGroupOptions, v as EmbeddingBatchUnavailableError } from "./memory-core-host-engine-embeddings-CX_qB4Zn.mjs";
import { t as parseGeminiAuth } from "./gemini-auth-CPHuN1jC.mjs";
import { a as isValidGeminiEmbeddingValues, o as sanitizeGeminiEmbedding } from "./embedding-provider-BKZJmSAJ.mjs";
//#region extensions/google/embedding-batch.ts
const GEMINI_BATCH_MAX_REQUESTS = 5e4;
function bindGeminiBatchAuth(e) {
const t = e.apiKeys[0];
if (!t) throw new Error("gemini batch requires an API key");
return {
...e,
headers: {
...parseGeminiAuth(t).headers,
...e.headers
}
};
}
function getGeminiBatchFileUrl(e, t, n) {
const r = new URL(e);
const i = r.pathname.replace(/\/+$/, "");
if (t === "upload" || r.origin === "https://generativelanguage.googleapis.com") {
const e = i.match(/^(.*)\/(v\d+(?:alpha|beta)?)$/);
r.pathname = e ? `${e[1]}/${t}/${e[2]}` : t === "upload" ? `${i}/upload` : i;
}
const a = t === "upload" ? n : `${n.startsWith("files/") ? n : `files/${n}`}:download`;
const o = new URL(resolveEmbeddingEndpointUrl(r.href, a));
o.searchParams.set(t === "upload" ? "uploadType" : "alt", t === "upload" ? "multipart" : "media");
return o.href;
}
function getGeminiBatchState(e) {
const t = e.metadata?.state?.replace(/^(?:BATCH|JOB)_STATE_/, "");
if (t === "FAILED") return "failed";
if (t === "CANCELLED" || t === "CANCELED") return "cancelled";
if (t === "EXPIRED") return "expired";
if (e.error) return "failed";
if (e.done === false) return "pending";
if (e.done === true) return "succeeded";
if (t === "SUCCEEDED") return "succeeded";
if (t === "PENDING" || t === "RUNNING") return "pending";
return "unknown";
}
function getGeminiBatchOutputFileId(e) {
const t = e.response?.responsesFile;
const n = e.metadata?.output?.responsesFile;
if (t && n && t !== n) throw new Error("gemini batch operation returned conflicting output files");
return t ?? n;
}
async function fetchGeminiBatchStatus(e) {
const t = e.batchName.startsWith("batches/") ? e.batchName : `batches/${e.batchName}`;
const n = resolveEmbeddingEndpointUrl(e.gemini.baseUrl, t);
debugEmbeddingsLog("memory embeddings: gemini batch status", { statusUrl: n });
return await withRemoteHttpResponse({
url: n,
ssrfPolicy: e.gemini.ssrfPolicy,
signal: e.signal,
init: { headers: buildBatchHeaders(e.gemini, { json: true }) },
onResponse: async (e) => {
await assertOkOrThrowProviderError(e, "gemini.batch-status");
return await readProviderJsonObjectResponse(e, "gemini.batch-status");
}
});
}
async function runGeminiEmbeddingBatches(e) {
const t = bindGeminiBatchAuth(e.gemini);
return await runEmbeddingBatchGroups({
...buildEmbeddingBatchGroupOptions(e, {
maxRequests: GEMINI_BATCH_MAX_REQUESTS,
debugLabel: "memory embeddings: gemini batch submit"
}),
runGroup: async ({ group: n, groupIndex: r, groups: i, byCustomId: a, pollIntervalMs: o, timeoutMs: s }) => {
const c = e.agentId;
const l = t.baseUrl;
const u = n.map((e) => JSON.stringify({
key: e.custom_id,
request: e.request
})).join("\n");
const d = `memory-embeddings-${sha256Hex(String(Date.now()))}`;
const f = `openclaw-${sha256Hex(d)}`;
const p = JSON.stringify({ file: {
displayName: d,
mimeType: "application/jsonl"
} });
const m = `--${f}\r\n`;
const h = `--${f}--\r\n`;
const g = [
`${m}Content-Type: application/json; charset=UTF-8\r\n\r\n${p}\r\n`,
`${m}Content-Type: application/jsonl; charset=UTF-8\r\n\r\n${u}\r\n`,
h
];
const _ = new Blob([g.join("")], { type: "multipart/related" });
const v = `multipart/related; boundary=${f}`;
const y = getGeminiBatchFileUrl(l, "upload", "files");
debugEmbeddingsLog("memory embeddings: gemini batch upload", {
uploadUrl: y,
baseUrl: l,
requests: n.length
});
const b = (await withRemoteHttpResponse({
url: y,
ssrfPolicy: t.ssrfPolicy,
init: {
method: "POST",
headers: {
...buildBatchHeaders(t, { json: false }),
"Content-Type": v
},
body: _
},
onResponse: async (e) => {
await assertOkOrThrowProviderError(e, "gemini.batch-file-upload");
return await readProviderJsonObjectResponse(e, "gemini.batch-file-upload");
}
})).file?.name;
if (!b) throw new Error("gemini batch file upload failed: missing file id");
const x = { batch: {
displayName: `memory-embeddings-${c}`,
inputConfig: { file_name: b }
} };
const S = resolveEmbeddingEndpointUrl(l, `${t.modelPath}:asyncBatchEmbedContent`);
debugEmbeddingsLog("memory embeddings: gemini batch create", {
batchEndpoint: S,
fileId: b
});
const C = await withRemoteHttpResponse({
url: S,
ssrfPolicy: t.ssrfPolicy,
init: {
method: "POST",
headers: buildBatchHeaders(t, { json: true }),
body: JSON.stringify(x)
},
onResponse: async (e) => {
if (e.status === 404) {
const t = await createProviderHttpError(e, "gemini.batch-create");
throw new EmbeddingBatchUnavailableError("gemini asyncBatchEmbedContent not available for this request", { cause: t });
}
await assertOkOrThrowProviderError(e, "gemini.batch-create");
return await readProviderJsonObjectResponse(e, "gemini.batch-create");
}
});
const w = C.name ?? "";
if (!w) throw new Error("gemini batch create failed: missing batch name");
e.debug?.("memory embeddings: gemini batch created", {
batchName: w,
state: getGeminiBatchState(C),
group: r + 1,
groups: i,
requests: n.length
});
const T = e.wait;
const E = e.debug;
const waitForBatch = async () => {
const e = createProviderOperationDeadline({
label: `gemini batch ${w}`,
timeoutMs: s
});
let n = C;
while (true) {
const r = n ? n : await fetchGeminiBatchStatus({
gemini: t,
batchName: w,
signal: AbortSignal.timeout(resolveProviderOperationTimeoutMs({
deadline: e,
defaultTimeoutMs: s
}))
});
const i = getGeminiBatchState(r);
if (i === "succeeded") {
const e = getGeminiBatchOutputFileId(r);
if (!e) throw new Error(`gemini batch ${w} completed without output file`);
return { outputFileId: e };
}
if (i === "failed" || i === "cancelled" || i === "expired") {
const e = r.error?.message ?? (r.error?.code === void 0 ? "unknown error" : `code ${r.error.code}`);
throw new Error(`gemini batch ${w} ${i}: ${formatBatchErrorDetail(e) ?? "unknown error"}`);
}
if (!T) throw new Error(`gemini batch ${w} submitted; enable remote.batch.wait to await completion`);
E?.(`gemini batch ${w} ${i}; waiting up to ${o}ms`);
await waitProviderOperationPollInterval({
deadline: e,
pollIntervalMs: o
});
n = void 0;
}
};
const D = await waitForBatch();
const O = [];
const k = new Set(n.map((e) => e.custom_id));
const A = D.outputFileId;
const j = getGeminiBatchFileUrl(t.baseUrl, "download", A);
debugEmbeddingsLog("memory embeddings: gemini batch download", { downloadUrl: j });
await withRemoteHttpResponse({
url: j,
ssrfPolicy: t.ssrfPolicy,
init: { headers: buildBatchHeaders(t, { json: true }) },
onResponse: async (e) => {
await assertOkOrThrowProviderError(e, "gemini.batch-file-content");
const applyOutputLine = (e) => {
const n = t.outputDimensionality;
const r = e.key ?? e.custom_id ?? e.request_id;
if (!r || !k.delete(r)) return;
const i = e.error?.message || e.response?.error?.message;
if (i) {
O.push(`${r}: ${i}`);
return;
}
const o = e.embedding?.values ?? e.response?.embedding?.values;
if (!isValidGeminiEmbeddingValues(o)) {
const e = o == null || Array.isArray(o) && o.length === 0 ? "empty" : "invalid";
O.push(`${r}: ${e} embedding`);
return;
}
a.set(r, sanitizeGeminiEmbedding(o, n));
};
await readEmbeddingBatchJsonl(e, {
label: "gemini.batch-file-content",
maxRecords: k.size,
onRecord: (e) => {
applyOutputLine(e);
return O.length === 0 && k.size > 0;
}
});
}
});
if (O.length > 0) throw new Error(`gemini batch ${w} failed: ${formatBatchErrorDetail(O[0]) ?? "unknown error"}`);
if (k.size > 0) throw new Error(`gemini batch ${w} missing ${k.size} embedding responses`);
}
});
}
//#endregion
export { runGeminiEmbeddingBatches as t };