openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 5.77 kB
JavaScript
import{n as coerceErrorMessage}from"../../error-coercion-DlKnt6w-.mjs";import{f as normalizeStringEntries}from"../../string-normalization-D_oBUpO3.mjs";import{g as readProviderTextResponse,h as readProviderJsonResponse,r as assertOkOrThrowProviderError}from"../../provider-http-errors-CWZQ78Qm.mjs";import{k as withRemoteHttpResponse}from"../../gateway-startup-plugin-config-DVImEAD3.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../error-runtime-DW-sj0iq.mjs";import{_ as resolveProviderOperationTimeoutMs,r as createProviderOperationDeadline,v as waitProviderOperationPollInterval}from"../../shared-BGvdIfYO.mjs";import"../../provider-http-D0sVd8r_.mjs";import{S as formatUnavailableBatchError,b as extractBatchErrorMessage,c as resolveEmbeddingEndpointUrl,d as buildEmbeddingBatchGroupOptions,g as EMBEDDING_BATCH_ENDPOINT,h as waitForEmbeddingBatch,m as buildBatchHeaders,o as uploadBatchJsonlFile,p as runEmbeddingBatches,v as postJsonWithRetry,x as formatBatchErrorDetail}from"../../memory-core-host-engine-embeddings-C93s8VS5.mjs";
//!extensions/openai/embedding-batch.ts
const OPENAI_BATCH_ENDPOINT=EMBEDDING_BATCH_ENDPOINT;const OPENAI_BATCH_COMPLETION_WINDOW=`24h`;const OPENAI_BATCH_MAX_REQUESTS=5e4;const OPENAI_BATCH_MAX_JSONL_BYTES=199229440;const OPENAI_BATCH_MAX_POLL_BACKOFF_MS=3e5;async function submitOpenAiBatch(e){const t=await uploadBatchJsonlFile({client:e.openAi,requests:e.requests,errorPrefix:`openai batch file upload failed`});return await postJsonWithRetry({url:resolveEmbeddingEndpointUrl(e.openAi.baseUrl,`batches`),headers:buildBatchHeaders(e.openAi,{json:true}),ssrfPolicy:e.openAi.ssrfPolicy,fetchImpl:e.openAi.fetchImpl,resolveRequestHeaders:e.openAi.resolveRequestHeaders,body:{input_file_id:t,endpoint:OPENAI_BATCH_ENDPOINT,completion_window:OPENAI_BATCH_COMPLETION_WINDOW,metadata:{source:`openclaw-memory`,agent:e.agentId}},errorPrefix:`openai batch create failed`})}async function fetchOpenAiBatchResource(e){return await withRemoteHttpResponse({url:resolveEmbeddingEndpointUrl(e.openAi.baseUrl,e.path),ssrfPolicy:e.openAi.ssrfPolicy,fetchImpl:e.openAi.fetchImpl,resolveRequestHeaders:e.openAi.resolveRequestHeaders,signal:e.signal,init:{headers:buildBatchHeaders(e.openAi,{json:true})},onResponse:async(t,n)=>{await assertOkOrThrowProviderError(t,e.label,{requestHeaders:n,signal:e.signal});return await e.parse(t)}})}function formatOpenAiBatchDiagnostic(e){return formatBatchErrorDetail(coerceErrorMessage(e))??`unknown error`}function isOpenAiBatchUploadTooLargeError(e){const t=coerceErrorMessage(e);if(!/openai batch file upload failed/i.test(t))return false;return/\b413\b/.test(t)||/payload too large/i.test(t)||/request body too large/i.test(t)||/file too large/i.test(t)||/maximum allowed/i.test(t)||/max(?:imum)? (?:body|payload|file) (?:size )?(?:exceeded|limit)/i.test(t)}function parseOpenAiBatchOutput(e){return normalizeStringEntries(e.split(`
`)).map(parseOpenAiBatchOutputLine)}function parseOpenAiBatchOutputLine(e){try{return JSON.parse(e)}catch{throw new Error(`OpenAI embedding batch output contained malformed JSONL`)}}async function readOpenAiBatchError(e){try{const t=parseOpenAiBatchOutput(await fetchOpenAiBatchResource({openAi:e.openAi,path:`/files/${e.errorFileId}/content`,label:`openai.batch-file-content`,parse:e=>readProviderTextResponse(e,`openai.batch-file-content`)}));return formatBatchErrorDetail(extractBatchErrorMessage(t))}catch(e){return formatUnavailableBatchError(e)}}function formatOpenAiBatchProgress(e){const t=e.request_counts;if(!t||typeof t.total!==`number`)return``;const n=typeof t.completed===`number`?t.completed:0;const r=typeof t.failed===`number`?t.failed:0;return`; progress ${n}/${t.total} failed=${r}`}function isRetryableOpenAiBatchPollError(e){const t=coerceErrorMessage(e);const n=e&&typeof e===`object`?e.status:void 0;return typeof n===`number`&&(n===408||n===409||n===425||n===429||n>=500&&n<=599)||/\b(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN)\b|fetch failed|network error/i.test(t)}async function runOpenAiEmbeddingBatches(e){return await runEmbeddingBatches({provider:`openai`,...buildEmbeddingBatchGroupOptions(e,{maxRequests:OPENAI_BATCH_MAX_REQUESTS,maxJsonlBytes:e.maxJsonlBytes??OPENAI_BATCH_MAX_JSONL_BYTES,debugLabel:`memory embeddings: openai batch submit`}),shouldSplitGroupOnError:isOpenAiBatchUploadTooLargeError,onSplitGroup:({error:t,group:n,parts:r,depth:i})=>{e.debug?.(`memory embeddings: openai batch upload too large; splitting group`,{requests:n.length,parts:r.map(e=>e.length),depth:i,error:formatOpenAiBatchDiagnostic(t)})},submit:t=>submitOpenAiBatch({openAi:e.openAi,requests:t,agentId:e.agentId}),readError:t=>readOpenAiBatchError({openAi:e.openAi,errorFileId:t}),readOutput:(t,n)=>fetchOpenAiBatchResource({openAi:e.openAi,path:`/files/${t}/content`,label:`openai.batch-file-content`,parse:n}),waitForBatch:async(t,n,r)=>{const i=t.id;const{openAi:a,wait:o,debug:s}=e;const c=createProviderOperationDeadline({label:`openai batch ${i}`,timeoutMs:r});return await waitForEmbeddingBatch({provider:`openai`,batchId:i,wait:o,pollIntervalMs:n,timeoutMs:r,debug:s,initial:t,fetchStatus:e=>fetchOpenAiBatchResource({openAi:a,path:`/batches/${i}`,label:`openai.batch-status`,signal:e,parse:e=>readProviderJsonResponse(e,`openai.batch-status`)}),resolveTimeoutMs:()=>resolveProviderOperationTimeoutMs({deadline:c,defaultTimeoutMs:r}),waitForPoll:e=>waitProviderOperationPollInterval({deadline:c,pollIntervalMs:e}),readError:async e=>await readOpenAiBatchError({openAi:a,errorFileId:e}),backoff:{maxDelayMs:OPENAI_BATCH_MAX_POLL_BACKOFF_MS,shouldRetry:isRetryableOpenAiBatchPollError,formatError:formatOpenAiBatchDiagnostic,formatProgress:formatOpenAiBatchProgress}})}})}export{OPENAI_BATCH_ENDPOINT,runOpenAiEmbeddingBatches};