import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
import{OpenAI}from"./chunk-NUHFSC37.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import{retryProviderRequest}from"./chunk-XNGRGP62.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord,providerHeadersToRecord}from"./chunk-6R7UI4IY.js";import"./chunk-4L3WN2XY.js";var generateImages=async(model,context,options)=>{let output={api:model.api,provider:model.provider,model:model.id,output:[],stopReason:"stop",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let client=createClient(model,apiKey,options?.headers,options?.fetch),params=buildParams(model,context),nextParams=await options?.onPayload?.(params,model);nextParams!==void 0&&(params=nextParams);let requestOptions={...options?.signal?{signal:options.signal}:{},...options?.timeoutMs!==void 0?{timeout:options.timeoutMs}:{},maxRetries:0},{data:response,response:rawResponse}=await retryProviderRequest(()=>client.chat.completions.create(params,requestOptions).withResponse(),{maxRetries:options?.maxRetries,maxRetryDelayMs:options?.maxRetryDelayMs,signal:options?.signal});await options?.onResponse?.({status:rawResponse.status,headers:headersToRecord(rawResponse.headers)},model);let imageResponse=response;output.responseId=imageResponse.id,imageResponse.usage&&(output.usage=parseUsage(imageResponse.usage,model));let choice=imageResponse.choices[0];if(choice){let content=choice.message.content;typeof content=="string"&&content.length>0&&output.output.push({type:"text",text:content});for(let image of choice.message.images??[]){let imageUrl=typeof image.image_url=="string"?image.image_url:image.image_url?.url;if(!imageUrl?.startsWith("data:"))continue;let matches=imageUrl.match(/^data:([^;]+);base64,(.+)$/);matches&&output.output.push({type:"image",mimeType:matches[1],data:matches[2]})}}return output}catch(error){return output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),output}};function createClient(model,apiKey,optionsHeaders,fetch){return new OpenAI({apiKey,baseURL:model.baseUrl,dangerouslyAllowBrowser:!0,fetch,defaultHeaders:providerHeadersToRecord({...model.headers,...optionsHeaders})})}function buildParams(model,context){let content=context.input.map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",image_url:{url:`data:${item.mimeType};base64,${item.data}`}});return{model:model.id,messages:[{role:"user",content}],stream:!1,modalities:model.output.includes("text")?["image","text"]:["image"]}}function parseUsage(rawUsage,model){let promptTokens=rawUsage.prompt_tokens||0,reportedCachedTokens=rawUsage.prompt_tokens_details?.cached_tokens||0,cacheWriteTokens=rawUsage.prompt_tokens_details?.cache_write_tokens||0,cacheReadTokens=cacheWriteTokens>0?Math.max(0,reportedCachedTokens-cacheWriteTokens):reportedCachedTokens,input=Math.max(0,promptTokens-cacheReadTokens-cacheWriteTokens),output=rawUsage.completion_tokens||0,usage={input,output,cacheRead:cacheReadTokens,cacheWrite:cacheWriteTokens,totalTokens:input+output+cacheReadTokens+cacheWriteTokens,cost:{input:model.cost.input/1e6*input,output:model.cost.output/1e6*output,cacheRead:model.cost.cacheRead/1e6*cacheReadTokens,cacheWrite:model.cost.cacheWrite/1e6*cacheWriteTokens,total:0}};return usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite,usage}export{generateImages};
