import{O as y}from"./client-DFw1b8C8.js";import{aa as R}from"./edit-CLPUkaSB.js";import{h as x}from"./headers-CgnjaPPL.js";import{s as _}from"./sanitize-unicode-cmozpu7l.js";import"./index-rvuS68Al.js";import"./vendor-mini-lit-Cx886NBU.js";import"./vendor-lit-BtHfzs80.js";import"./vendor-lucide-DBEJLfdn.js";import"./vendor-marked-_iteVaMm.js";import"./vendor-sortable-B1o3v0Qs.js";import"./ident-CvQrffF1.js";const C=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 i=k(e,s,t?.headers);let n=w(e,r);const c=await t?.onPayload?.(n,e);c!==void 0&&(n=c);const o={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},...t?.maxRetries!==void 0?{maxRetries:t.maxRetries}:{}},{data:l,response:g}=await i.chat.completions.create(n,o).withResponse();await t?.onResponse?.({status:g.status,headers:x(g.headers)},e);const p=l;a.responseId=p.id,p.usage&&(a.usage=b(p.usage,e));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 d of u.message.images??[]){const f=typeof d.image_url=="string"?d.image_url:d.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 w(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 b(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,i=s>0?Math.max(0,a-s):a,n=Math.max(0,t-i-s),c=e.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{C as generateImagesOpenRouter};
