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