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