import{O as y}from"./client-Sq9UPDIz.js";import{g as R}from"./env-api-keys.browser-DGvvjVWg.js";import{h as x}from"./headers-CgnjaPPL.js";import{s as _}from"./sanitize-unicode-B62XMGgN.js";const O=async(e,r,t)=>{const a={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:"stop",timestamp:Date.now()};try{const s=t?.apiKey||R(e.provider);if(!s)throw new Error(`No API key available for provider: ${e.provider}`);const c=k(e,s,t?.headers);let n=v(e,r);const i=await t?.onPayload?.(n,e);i!==void 0&&(n=i);const o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},{data:l,response:d}=await c.chat.completions.create(n,o).withResponse();await t?.onResponse?.({status:d.status,headers:x(d.headers)},e);const u=l;a.responseId=u.id,u.usage&&(a.usage=w(u.usage,e));const p=u.choices[0];if(p){const m=p.message.content;typeof m=="string"&&m.length>0&&a.output.push({type:"text",text:m});for(const g of p.message.images??[]){const f=typeof g.image_url=="string"?g.image_url:g.image_url?.url;if(!f?.startsWith("data:"))continue;const h=f.match(/^data:([^;]+);base64,(.+)$/);h&&a.output.push({type:"image",mimeType:h[1],data:h[2]})}}return a}catch(s){return a.stopReason=t?.signal?.aborted?"aborted":"error",a.errorMessage=s instanceof Error?s.message:JSON.stringify(s),a}};function k(e,r,t){return new y({apiKey:r,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...e.headers,...t}})}function v(e,r){const t=r.input.map(a=>a.type==="text"?{type:"text",text:_(a.text)}:{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}});return{model:e.id,messages:[{role:"user",content:t}],stream:!1,modalities:e.output.includes("text")?["image","text"]:["image"]}}function w(e,r){const t=e.prompt_tokens||0,a=e.prompt_tokens_details?.cached_tokens||0,s=e.prompt_tokens_details?.cache_write_tokens||0,c=s>0?Math.max(0,a-s):a,n=Math.max(0,t-c-s),i=e.completion_tokens||0,o={input:n,output:i,cacheRead:c,cacheWrite:s,totalTokens:n+i+c+s,cost:{input:r.cost.input/1e6*n,output:r.cost.output/1e6*i,cacheRead:r.cost.cacheRead/1e6*c,cacheWrite:r.cost.cacheWrite/1e6*s,total:0}};return o.cost.total=o.cost.input+o.cost.output+o.cost.cacheRead+o.cost.cacheWrite,o}export{O as generateImagesOpenRouter};
