"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("openai"),w=require("openai/core"),f=require("openai/streaming"),Y=require("crypto"),se=require("openai/pagination"),K=require("node:crypto"),P=require("openai/uploads");let m=class{constructor(e){this._client=e}};const ne=a=>a instanceof Error?a:new Error(a);function H(a){return Array.isArray(a)?a:[a]}function R(a,e){return Math.floor(Math.random()*(e-a+1))+a}let oe=class y extends m{constructor(){super(...arguments),this.endpoints={"ernie-bot":"/chat/completions","ernie-bot-turbo":"/chat/eb-instant","ernie-bot-4":"/chat/completions_pro","ernie-bot-8k":"/chat/ernie_bot_8k"}}async create(e,t){var l;const{model:r="ernie-bot",...s}=y.buildCreateParams(e),n=this.endpoints[r];if(!n)throw new u.OpenAIError(`Invalid model: ${r}`);const o=s.stream,i={...t==null?void 0:t.headers,Accept:o?"text/event-stream":"application/json"},c=await this._client.post(n,{...t,body:s,headers:i,stream:!1,__binaryResponse:!0});if(o){const d=new AbortController;return(l=t==null?void 0:t.signal)==null||l.addEventListener("abort",()=>{d.abort()}),y.fromOpenAIStream(r,f.Stream.fromSSEResponse(c,d),d)}return y.fromResponse(r,await c.json())}static buildCreateParams(e){const{messages:t=[],presence_penalty:r,user:s,stop:n,...o}=e,i=t[0],c=i&&i.role==="system"?i.content:void 0;c&&t.splice(0,1);const l={...o,messages:t};return c&&(l.system=c),s&&(l.user_id=s),r&&(l.penalty_score=r),n&&(l.stop=H(n)),l}static fromResponse(e,t){y.assert(t);const r=t.result,s={index:0,message:{role:"assistant",content:r.result},logprobs:null,finish_reason:"stop"};return r.is_end?s.finish_reason="stop":r.is_truncated?s.finish_reason="length":r.need_clear_history&&(s.finish_reason="content_filter"),{id:r.id,model:e,choices:[s],created:parseInt(r.created,10),object:"chat.completion",usage:r.usage}}static fromOpenAIStream(e,t,r){async function*s(){for await(const n of t){y.assert(n);const o=n.result,i={index:0,delta:{role:"assistant",content:o.result||""},finish_reason:null};o.is_end?i.finish_reason="stop":o.is_truncated?i.finish_reason="length":o.need_clear_history&&(i.finish_reason="content_filter"),yield{id:o.id,model:e,choices:[i],object:"chat.completion.chunk",created:parseInt(o.created,10),usage:o.usage}}}return new f.Stream(s,r)}static makeAPIError(e,t){const r={code:e,message:t};switch(e){case 2:return u.APIError.generate(500,r,t,{});case 6:case 111:return u.APIError.generate(403,r,t,{});case 17:case 18:case 19:case 40407:return u.APIError.generate(429,r,t,{});case 110:case 40401:return u.APIError.generate(401,r,t,{});case 336003:return u.APIError.generate(400,r,t,{});case 336100:return u.APIError.generate(500,r,t,{});default:return u.APIError.generate(void 0,r,t,{})}}static assert(e){if(e.errorCode!==0)throw y.makeAPIError(e.errorCode,e.errorMsg)}},ae=class extends m{constructor(){super(...arguments),this.completions=new oe(this._client)}},ie=class j extends m{constructor(){super(...arguments),this.endpoints={"ernie-text-embedding":"/embeddings/embedding-v1"}}async create(e,t){const{model:r,user:s,input:n}=e,o=this.endpoints[r];if(!o)throw new u.OpenAIError(`Invalid model: ${r}`);const i={input:n,user_id:s},c=await this._client.post(o,{body:i,...t,__binaryResponse:!0});return j.fromResponse(r,await c.json())}static fromResponse(e,t){j.assert(t);const{result:r}=t;return{data:r.data,model:e,object:"list",usage:r.usage}}static assert(e){if(e.errorCode===0)return;const t={code:e.errorCode,message:e.errorMsg};throw u.APIError.generate(void 0,t,void 0,void 0)}};class ce extends w.APIClient{constructor(e={}){const{apiKey:t=process.env.EB_API_KEY||"",baseURL:r="https://aistudio.baidu.com/llm/lmapi/v1",timeout:s=3e4,fetch:n=globalThis.fetch,httpAgent:o=void 0,...i}=e;super({baseURL:r,timeout:s,fetch:n,httpAgent:o,...i}),this.chat=new ae(this),this.embeddings=new ie(this),this._options=e,this.apiKey=t}authHeaders(){return{Authorization:`token ${this.apiKey}`}}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}defaultQuery(){return this._options.defaultQuery}}const le=ce;let L=class{constructor(e){this._client=e}},ue=class extends L{async create(e,t){var c;const{stream:r,model:s}=e,n=this.buildCreateParams(e),o=`/models/${s}:generateContent`,i=await this._client.post(o,{...t,query:r?{alt:"sse"}:{},body:n,stream:!1,__binaryResponse:!0});if(r){const l=new AbortController;return(c=t==null?void 0:t.signal)==null||c.addEventListener("abort",()=>{l.abort()}),this.afterSSEResponse(s,i,l)}return this.afterResponse(s,i)}buildCreateParams(e){const{messages:t=[],max_tokens:r,top_p:s,top_k:n,stop:o,temperature:i}=e;function c(h){const g=[];if(typeof h=="string")return g.push({text:h}),g;for(const _ of h)_.type==="text"&&g.push({text:_.text});return g}function l(h){return h==="user"?"user":"model"}const d={},p={contents:t.map(h=>({role:l(h.role),parts:c(h.content)})),generationConfig:d};return i!=null&&(d.temperature=i),n!=null&&(d.topK=n),s!=null&&(d.topP=s),o!=null&&(d.stopSequences=H(o)),r!=null&&(d.maxOutputTokens=r),p}async afterResponse(e,t){const s=(await t.json()).candidates.map(n=>{const[o]=n.content.parts,i={index:n.index,message:{role:"assistant",content:o.text},logprobs:null,finish_reason:"stop"};switch(n.finishReason){case"MAX_TOKENS":i.finish_reason="length";break;case"SAFETY":case"RECITATION":i.finish_reason="content_filter";break;default:i.finish_reason="stop"}return i});return{id:Y.randomUUID(),model:e,choices:s,object:"chat.completion",created:Date.now()/10,usage:{completion_tokens:0,prompt_tokens:0,total_tokens:0}}}afterSSEResponse(e,t,r){const s=f.Stream.fromSSEResponse(t,r),n=i=>i.candidates.map(c=>{const[l]=c.content.parts,d={index:c.index,delta:{role:"assistant",content:l.text||""},finish_reason:null};switch(c.finishReason){case"MAX_TOKENS":d.finish_reason="length";break;case"SAFETY":case"RECITATION":d.finish_reason="content_filter";break;default:d.finish_reason="stop"}return d});async function*o(){for await(const i of s)yield{id:Y.randomUUID(),model:e,choices:n(i),object:"chat.completion.chunk",created:Date.now()/10}}return new f.Stream(o,r)}},de=class extends L{constructor(){super(...arguments),this.completions=new ue(this._client)}};class $ extends L{async retrieve(e,t){return{id:(await this._client.get(`/models/${e}`,t)).name,created:0,object:"model",owned_by:"google"}}list(e){return this._client.getAPIList("/models",he,e)}}class he extends se.Page{constructor(e,t,r,s){const n=r.models.map(o=>({id:o.name,created:0,object:"model",owned_by:"google"}));super(e,t,{data:n,object:"list"},s)}}(a=>{a.Model=u.Models.Model,a.ModelsPage=u.Models.ModelsPage})($||($={}));const pe="https://generativelanguage.googleapis.com/v1";class me extends w.APIClient{constructor(e={}){const{apiKey:t=process.env.GEMINI_API_KEY||"",baseURL:r=process.env.GEMINI_BASE_URL||pe,timeout:s=3e4,fetch:n=globalThis.fetch,httpAgent:o=void 0,...i}=e;super({baseURL:r,timeout:s,fetch:n,httpAgent:o,...i}),this.chat=new de(this),this.models=new $(this),this._options=e,this.apiKey=t}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}defaultQuery(){return{...this._options.defaultQuery,key:this.apiKey}}}const fe=me;let F=class{constructor(e){this._client=e}},ge=class D extends F{async create(e,t){var _;const r=this._client,{model:s,messages:n,temperature:o=.8,top_p:i,stream:c}=e,l=Math.floor(Date.now()/1e3),d={app_id:r.appId,secret_id:r.secretId,timestamp:l,expired:l+7200,temperature:o,top_p:i,stream:c?1:0,messages:n},p="/chat/completions",h=r.generateAuthorization(p,d),g=await this._client.post(p,{...t,body:d,headers:{...t==null?void 0:t.headers,Authorization:h},stream:!1,__binaryResponse:!0});if(e.stream){const b=new AbortController;return(_=t==null?void 0:t.signal)==null||_.addEventListener("abort",()=>{b.abort()}),D.fromSSEResponse(s,f.Stream.fromSSEResponse(g,b),b)}return D.fromResponse(s,await g.json())}static fromSSEResponse(e,t,r){async function*s(){for await(const n of t){if(n.error)throw new u.APIError(void 0,n.error,void 0,void 0);const i={index:0,delta:{role:"assistant",content:n.choices[0].delta.content||""},finish_reason:null};yield{id:n.id,model:e,choices:[i],object:"chat.completion.chunk",created:parseInt(n.created,10)}}}return new f.Stream(s,r)}static fromResponse(e,t){if(t.error)throw new u.APIError(void 0,t.error,void 0,void 0);const r=t.choices[0],s={index:0,message:{role:"assistant",content:r.messages.content},logprobs:null,finish_reason:r.finish_reason};return{id:t.id,model:e,choices:[s],created:parseInt(t.created),object:"chat.completion",usage:t.usage}}hash(e){return K.createHmac("sha1",this._client.secretKey).update(Buffer.from(e,"utf8")).digest("base64")}},_e=class extends F{constructor(){super(...arguments),this.completions=new ge(this._client)}};class be extends w.APIClient{constructor(e={}){const{appId:t=process.env.HUNYUAN_APP_ID||"",secretId:r=process.env.HUNYUAN_SECRET_ID||"",secretKey:s=process.env.HUNYUAN_SECRET_KEY||"",baseURL:n="https://hunyuan.cloud.tencent.com/hyllm/v1",timeout:o=3e4,fetch:i=globalThis.fetch,httpAgent:c=void 0,...l}=e;super({baseURL:n,timeout:o,fetch:i,httpAgent:c,...l}),this.chat=new _e(this),this._options=e,this.appId=parseInt(t,10),this.secretKey=s,this.secretId=r}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}defaultQuery(){return this._options.defaultQuery}generateAuthorization(e,t){const r=this.buildURL(e,{}).replace("https://",""),s=[];return Object.keys(t).sort().forEach(n=>{const o=t[n];o!=null&&(typeof o=="object"?s.push(`${n}=${JSON.stringify(o)}`):s.push(`${n}=${o}`))}),this.hash(`${r}?${s.join("&")}`)}hash(e){return K.createHmac("sha1",this.secretKey).update(Buffer.from(e,"utf8")).digest("base64")}}const ye=be;async function*z(a,e,t){if(!a.body)throw t.abort(),new u.OpenAIError("Attempted to iterate over a response with no body");const r=new k,s=J(a.body);for await(const n of s)for(const o of r.decode(n)){const i=e.decode(o);i&&(yield i)}for(const n of r.flush()){const o=e.decode(n);o&&(yield o)}}class G{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const n={event:this.event,data:this.data.join(` `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=we(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}const I=class I{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const r=I.NEWLINE_CHARS.has(t[t.length-1]||"");let s=t.split(I.NEWLINE_REGEXP);return s.length===1&&!r?(this.buffer.push(s[0]),[]):(this.buffer.length>0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),r||(this.buffer=[s.pop()||""]),s)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new u.OpenAIError(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new u.OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new u.OpenAIError("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};I.NEWLINE_CHARS=new Set([` `,"\r","\v","\f","","","","…","\u2028","\u2029"]),I.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;let k=I;function we(a,e){const t=a.indexOf(e);return t!==-1?[a.substring(0,t),e,a.substring(t+e.length)]:[a,"",""]}function J(a){if(a[Symbol.asyncIterator])return a;const e=a.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}function B(a){if(a.base_resp.status_code===0)return;const e={code:a.base_resp.status_code,message:a.base_resp.status_msg};throw new u.APIError(void 0,e,void 0,void 0)}let Ae=class N extends m{constructor(){super(...arguments),this.resources={"abab5-chat":{model:"abab5-chat",endpoint:"/text/chatcompletion"},"abab5.5-chat":{model:"abab5.5-chat",endpoint:"/text/chatcompletion"},"abab5.5-chat-pro":{model:"abab5.5-chat",endpoint:"/text/chatcompletion_pro"}},this.system="MM智能助理是一款由MiniMax自研的,没有调用其他产品的接口的大型语言模型。MiniMax是一家中国科技公司,一直致力于进行大模型相关的研究。"}async create(e,t){var o;const r=this.resources[e.model];if(!r)throw new u.OpenAIError(`Invalid model: ${e.model}`);const s=this.buildCreateParams(e),n=await this._client.post(r.endpoint,{...t,body:{...s,model:r.model},stream:!1,__binaryResponse:!0});if(s.stream){const i=new AbortController;return(o=t==null?void 0:t.signal)==null||o.addEventListener("abort",()=>{i.abort()}),N.fromSSEResponse(e.model,n,i)}return N.fromResponse(e.model,await n.json())}buildCreateParams(e){const{model:t,messages:r=[],max_tokens:s,...n}=e,o={model:t,messages:[],...n};s&&(o.tokens_to_generate=s);const i=r[0],c=i&&i.role==="system"?i.content:null;return c&&r.splice(0,1),t==="abab5.5-chat-pro"?(o.bot_setting=[{bot_name:"MM智能助理",content:c||this.system}],o.reply_constraints={sender_type:"BOT",sender_name:"MM智能助理"}):(o.role_meta={bot_name:"MM智能助理",user_name:"用户"},o.prompt=c||this.system),o.messages=r.map(l=>{switch(l.role){case"assistant":return{sender_type:"BOT",text:l.content};default:{const d={sender_type:"USER",text:l.content};return t=="abab5.5-chat-pro"&&(d.sender_name="用户"),d}}}),e.stream&&(o.use_standard_sse=!0),o}static fromResponse(e,t){return B(t),{id:t.id,model:t.model,choices:t.choices.map((r,s)=>{const{finish_reason:n}=r;return e==="abab5.5-chat-pro"?{index:s,message:{role:"assistant",content:r.messages[0].text},logprobs:null,finish_reason:n}:{index:s,message:{role:"assistant",content:r.text},logprobs:null,finish_reason:n}}),created:t.created,object:"chat.completion",usage:t.usage}}static fromSSEResponse(e,t,r){let s=!1;const n=new G;function o(c){return{id:c.request_id,model:e,choices:c.choices.map((l,d)=>{const{finish_reason:p=null}=l;if(e==="abab5.5-chat-pro"){const h=l.messages[0].text;return{index:d,delta:{role:"assistant",content:p==="stop"?"":h},finish_reason:p}}return{index:d,delta:{role:"assistant",content:l.delta},finish_reason:p}}),object:"chat.completion.chunk",created:c.created}}async function*i(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(const l of z(t,n,r))if(!c){if(l.data.startsWith("[DONE]")){c=!0;continue}if(l.event===null){let d;try{d=JSON.parse(l.data)}catch(p){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),p}if(d&&d.code)throw new u.APIError(void 0,d,void 0,void 0);yield o(d)}}c=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{c||r.abort()}}return new f.Stream(i,r)}},Ee=class extends m{constructor(){super(...arguments),this.completions=new Ae(this._client)}};class Ie extends m{constructor(){super(...arguments),this.resources={"speech-01":{model:"speech-01",endpoint:"/text_to_speech",resposne_type:"binary"},"speech-01-pro":{model:"speech-01",endpoint:"/t2a_pro",resposne_type:"json"}}}async create(e,t){const{input:r,voice:s,...n}=e,o=this.resources[e.model];if(!o)throw new u.OpenAIError(`Invalid model: ${e.model}`);const i={...n,text:r,model:o.model};s&&(i.voice_id=s);const c=await this._client.post(o.endpoint,{...t,body:i,__binaryResponse:!0});return t!=null&&t.__binaryResponse||o.resposne_type==="binary"||o.resposne_type==="stream"?c:c.json().then(l=>(B(l),fetch(l.audio_file)))}}class ve extends m{constructor(){super(...arguments),this.speech=new Ie(this._client)}}let xe=class extends m{async create(e,t){const{model:r,input:s,type:n="query"}=e,i=await(await this._client.post("/embeddings",{body:{model:r,texts:s,type:n},...t,__binaryResponse:!0})).json();return B(i),{data:i.vectors.map((c,l)=>({embedding:c,index:l,object:"embedding"})),model:r,object:"list",usage:{prompt_tokens:i.total_tokens,total_tokens:i.total_tokens}}}};class Se extends w.APIClient{constructor(e={}){const{orgId:t=process.env.MINIMAX_API_ORG||"",apiKey:r=process.env.MINIMAX_API_KEY||"",baseURL:s="https://api.minimax.chat/v1",timeout:n=3e4,fetch:o=globalThis.fetch,httpAgent:i=void 0,...c}=e;super({baseURL:s,timeout:n,fetch:o,httpAgent:i,...c}),this.audio=new ve(this),this.chat=new Ee(this),this.embeddings=new xe(this),this._options=e,this.apiKey=r,this.orgId=t}authHeaders(){return{Authorization:`Bearer ${this.apiKey}`}}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}defaultQuery(){return{GroupId:this.orgId,...this._options.defaultQuery}}}const Ce=Se;function W(a){return a.startsWith("qwen-vl")}function Q(a){return W(a)?"/services/aigc/multimodal-generation/generation":"/services/aigc/text-generation/generation"}function Pe(a){const{model:e,prompt:t,response_format:r,stream_options:s,...n}=a,o={model:e,input:{prompt:t},parameters:n};if(r&&r.type&&(o.parameters.result_format=r.type),a.stream){const{incremental_output:i}=s||{};o.parameters.incremental_output=i??!0}return o}function Re(a,e){return a==="null"||!a?e?null:"stop":a}function X(a){const{output_tokens:e,input_tokens:t,total_tokens:r=e+t}=a;return{completion_tokens:e,prompt_tokens:t,total_tokens:r}}function V(a,e,t){const{model:r}=a,{output:s,usage:n}=e,o={index:0,text:s.text,logprobs:null,finish_reason:Re(s.finish_reason,t)};return{id:e.request_id,model:r,choices:[o],created:Math.floor(Date.now()/1e3),object:"text_completion",usage:X(n)}}function ke(a,e,t){let r=!1;async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const o of f._iterSSEMessages(e,t))if(!n){if(o.data.startsWith("[DONE]")){n=!0;continue}if(o.event==="result"){let i;try{i=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(i&&i.code)throw new u.APIError(void 0,i,void 0,void 0);yield V(a,i,!0)}}n=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{n||t.abort()}}return new f.Stream(s,t)}function Te(a){return a.map(e=>(Array.isArray(e.content)?e.content.forEach(t=>{t.type==="image_url"&&(t.image=t.image_url.url,delete t.image_url),delete t.type}):e.content=[{text:e.content}],e))}function Me(a){return a.map(e=>{if(Array.isArray(e.content)){const t=e.content.find(r=>r.type==="text");return{role:e.role,content:t.text}}return e})}function Oe(a){const{model:e,messages:t,raw:r,response_format:s,stream_options:n={},...o}=a,i={model:e,input:{messages:[]},parameters:o};if(r===!0?i.input.messages=t:W(e)?i.input.messages=Te(t):i.input.messages=Me(t),a.tools)i.parameters.result_format="message";else if(s&&s.type&&(i.parameters.result_format=s.type),a.stream){const c=(n==null?void 0:n.incremental_output)??!0;i.parameters.incremental_output=c}return i}function T(a,e){return a==="null"||!a?e?null:"stop":a}function je(a,e){const{model:t}=a,{output:r,usage:s}=e,n={index:0,message:{role:"assistant",content:""},logprobs:null,finish_reason:"stop"};if(r.choices){const{message:o,finish_reason:i}=r.choices[0];n.message={role:o.role,content:o.content},i==="tool_calls"?(n.finish_reason="tool_calls",n.message.tool_calls=o.tool_calls):n.finish_reason=T(i,!0)}else n.message.content=r.text,n.finish_reason=T(r.finish_reason);return{id:e.request_id,model:t,choices:[n],created:Math.floor(Date.now()/1e3),object:"chat.completion",usage:X(s)}}function $e(a,e){const t=e.output,r={index:0,delta:{role:"assistant",content:""},finish_reason:null};if(t.choices){const{message:s,finish_reason:n}=t.choices[0];r.delta={role:s.role,content:s.content},n==="tool_calls"?(r.finish_reason="tool_calls",r.delta.tool_calls=s.tool_calls):r.finish_reason=T(n,!0)}else r.delta.content=t.text,r.finish_reason=T(t.finish_reason,!0);return{id:e.request_id,model:a.model,choices:[r],object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3)}}function De(a,e,t){let r=!1;async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let n=!1;try{for await(const o of f._iterSSEMessages(e,t))if(!n){if(o.data.startsWith("[DONE]")){n=!0;continue}if(o.event==="result"){let i;try{i=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(i&&i.code)throw new u.APIError(void 0,i,void 0,void 0);yield $e(a,i)}}n=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{n||t.abort()}}return new f.Stream(s,t)}let Ne=class extends m{async create(e,t){var i;const r={...t==null?void 0:t.headers};e.stream&&(r.Accept="text/event-stream");const s=Q(e.model),n=Oe(e),o=await this._client.post(s,{...t,body:n,headers:r,stream:!1,__binaryResponse:!0});if(e.stream){const c=new AbortController;return(i=t==null?void 0:t.signal)==null||i.addEventListener("abort",()=>{c.abort()}),De(n,o,c)}return je(n,await o.json())}},Z=class extends m{constructor(){super(...arguments),this.completions=new Ne(this._client)}},ee=class extends m{async create(e,t){var i;const r={...t==null?void 0:t.headers};e.stream&&(r.Accept="text/event-stream");const s=Q(e.model),n=Pe(e),o=await this._client.post(s,{...t,body:n,headers:r,stream:!1,__binaryResponse:!0});if(e.stream){const c=new AbortController;return(i=t==null?void 0:t.signal)==null||i.addEventListener("abort",()=>{c.abort()}),ke(n,o,c)}return V(n,await o.json())}},te=class extends m{async generate(e,t={}){const r=this._client,{headers:s,...n}=t,{model:o="wanx-v1",prompt:i,n:c=1,cfg:l,...d}=e,p=await r.post("/services/aigc/text2image/image-synthesis",{...n,headers:{"X-DashScope-Async":"enable",...s},body:{model:o,input:{prompt:i},parameters:{...d,scale:l,n:c}},__binaryResponse:!0}).then(h=>h.json()).then(h=>h.output.task_id);return this.waitTask(p,t).then(h=>({created:Date.now()/1e3,data:h}))}async waitTask(e,t){const r=await this._client.get(`/tasks/${e}`,{...t,__binaryResponse:!0}).then(o=>o.json()),{task_status:s,message:n}=r.output;if(s==="PENDING"||s==="RUNNING")return new Promise(o=>{setTimeout(()=>o(this.waitTask(e,t)),5e3)});if(s==="SUCCEEDED")return r.output.results.filter(o=>"url"in o);throw s==="FAILED"?new u.OpenAIError(n):new u.OpenAIError("Unknown task status")}};function Ue(a){return{model:a.model,input:{texts:a.input},parameters:{text_type:a.type||"query"}}}function Ke(a,e){const{output:t,usage:r}=e;return{object:"list",model:a.model,data:t.embeddings.map(({text_index:s,embedding:n})=>({index:s,embedding:n,object:"embedding"})),usage:{prompt_tokens:r.total_tokens,total_tokens:r.total_tokens}}}class re extends m{async create(e,t){const r=Ue(e),s=await this._client.post("/services/embeddings/text-embedding/text-embedding",{...t,body:r,__binaryResponse:!0});return Ke(e,await s.json())}}class U extends w.APIClient{constructor(e={}){const{apiKey:t=process.env.QWEN_API_KEY||"",baseURL:r="https://dashscope.aliyuncs.com/api/v1/",timeout:s=3e4,fetch:n=globalThis.fetch,httpAgent:o=void 0,...i}=e;super({baseURL:r,timeout:s,fetch:n,httpAgent:o,...i}),this.chat=new Z(this),this.completions=new ee(this),this.embeddings=new re(this),this.images=new te(this),this._options=e,this.apiKey=t}authHeaders(){return{Authorization:`Bearer ${this.apiKey}`}}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}defaultQuery(){return this._options.defaultQuery}async fetchWithTimeout(e,t,r,s){const n=await super.fetchWithTimeout(e,t,r,s);if(n.ok)return n;const o=n.headers.get("content-type")||"",i=await n.text().then(c=>{if(o.includes("text/event-stream")){const[l,d]=c.split("data:");return d}return c});return new Response(i,{status:n.status,statusText:n.statusText,headers:n.headers})}makeStatusError(e,t,r,s){return u.APIError.generate(e,{error:t},r,s)}}(a=>{a.Chat=Z,a.ChatModel=void 0,a.ChatCompletionCreateParams=void 0,a.ChatCompletionCreateParamsNonStreaming=void 0,a.ChatCompletionCreateParamsStreaming=void 0,a.Completions=ee,a.CompletionModel=void 0,a.Embeddings=re,a.Images=te})(U||(U={}));const He=U;let q=class{constructor(e){this._client=e}};class Le extends q{constructor(){super(...arguments),this.resources={"spark-1.5":{domain:"general",url:"wss://spark-api.xf-yun.com/v1.1/chat"},"spark-2":{domain:"generalv2",url:"wss://spark-api.xf-yun.com/v2.1/chat"},"spark-3":{domain:"generalv3",url:"wss://spark-api.xf-yun.com/v3.1/chat"}}}async create(e,t){const{model:r,messages:s,functions:n,user:o,...i}=e,c=this.resources[r],l=this._client.generateAuthorizationURL(c.url,"GET"),d={header:{app_id:this._client.appId},parameter:{chat:{...i,domain:c.domain}},payload:{message:{text:s}}};n&&(d.payload.functions={text:n}),o&&(d.header.uid=o);const p=new AbortController;t!=null&&t.signal&&t.signal.addEventListener("abort",()=>{p.abort()});const h=new globalThis.WebSocket(l);if(h.onopen=()=>{h.send(JSON.stringify(d))},e.stream){const g=new ReadableStream({pull(_){const b=new TextEncoder;h.onmessage=v=>{const x=JSON.parse(v.data),{header:A,payload:S}=x;if(A.code!==0){_.error(new u.APIError(void 0,x.header,void 0,void 0));return}const M=S.choices.text,[E]=M,C={index:0,delta:{role:E.role,content:E.content},finish_reason:null};A.status===2&&(C.finish_reason="stop"),E.function_call&&(C.delta.function_call=E.function_call);const O={id:A.sid,model:r,choices:[C],object:"chat.completion.chunk",created:Date.now()/1e3};_.enqueue(b.encode(JSON.stringify(O)+` `))},h.onerror=v=>{_.error(v)}},cancel(){h.close()}});return p.signal.addEventListener("abort",()=>{h.close()}),f.Stream.fromReadableStream(g,p)}return new Promise((g,_)=>{h.onmessage=b=>{const v=JSON.parse(b.data),{header:x,payload:A}=v;if(x.status!==2)return;const S=A.usage.text,M=A.choices.text,[E]=M,C={index:0,message:{role:"assistant",content:E.content},logprobs:null,finish_reason:"stop"},O={id:x.sid,object:"chat.completion",created:Date.now()/1e3,model:r,choices:[C],usage:{completion_tokens:S.completion_tokens,total_tokens:S.total_tokens,prompt_tokens:S.prompt_tokens}};g(O)},h.onerror=b=>_(b)})}}class Be extends q{constructor(){super(...arguments),this.completions=new Le(this._client)}}let qe=class extends q{async generate(e,t){const{prompt:r,user:s}=e,n={header:{app_id:this._client.appId,uid:s},parameter:{chat:{max_tokens:4096,domain:"general",temperature:.5}},payload:{message:{text:[{role:"user",content:r}]}}},o=this._client.generateAuthorizationURL("https://spark-api.cn-huabei-1.xf-yun.com/v2.1/tti","POST"),c=await(await this._client.post(o,{...t,body:n,__binaryResponse:!0})).json();if(c.header.code>0)throw new u.APIError(void 0,c.header,void 0,void 0);return{created:Date.now()/1e3,data:[{url:c.payload.choices.text[0].content}]}}};class Ye extends w.APIClient{constructor(e={}){const{appId:t=process.env.SPARK_APP_ID||"",apiKey:r=process.env.SPARK_API_KEY||"",apiSecret:s=process.env.SPARK_API_SECRET||"",baseURL:n="https://spark-api.xf-yun.com",timeout:o=3e4,fetch:i=globalThis.fetch,httpAgent:c=void 0,...l}=e;super({baseURL:n,timeout:o,fetch:i,httpAgent:c,...l}),this.chat=new Be(this),this.images=new qe(this),this._options=e,this.appId=t,this.apiKey=r,this.apiSecret=s}defaultQuery(){return this._options.defaultQuery}generateAuthorizationURL(e,t="GET"){const r=new URL(e,this.baseURL),s=new Date().toUTCString(),n=this.generateAuthorization({method:t,path:r.pathname,host:r.host,date:s});return r.searchParams.set("authorization",n),r.searchParams.set("host",r.host),r.searchParams.set("date",s),r.toString()}generateAuthorization({method:e,host:t,path:r,date:s}){const n=`host: ${t} date: ${s} ${e} ${r} HTTP/1.1`,o=this.hash(n);return globalThis.btoa(`api_key="${this.apiKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${o}"`)}hash(e){const t=K.createHmac("sha256",this.apiSecret);return t.update(e),t.digest("base64")}}const Fe=Ye;class ze{constructor(e){this._client=e}}class Ge extends ze{constructor(){super(...arguments),this.models={"imagine-v5":33,"anime-v5":34,"imagine-v4.1":32,"imagine-v4":31,"imagine-v3":30,"imagine-v1":28,realistic:29,anime:21,portrait:26,"sdxl-1.0":122}}async createVariation(e,t){const r=this._client,s=new FormData,{model:n,style:o=this.models[n??"realistic"]}=e;return s.append("image",await P.toFile(e.image)),s.append("style_id",(o||29).toString()),s.append("prompt",e.prompt),s.append("negative_prompt",e.negative_prompt||""),s.append("strength",(e.strength||0).toString()),s.append("steps",(e.steps||30).toString()),s.append("cfg",(e.cfg||7.5).toString()),s.append("seed",(e.seed||R(1,1e6)).toString()),{data:[{binary:(await r.post(`/imagine/${r.apiType}/generations/variations`,{...t,body:{body:s,[Symbol.toStringTag]:"MultipartBody"},__binaryResponse:!0})).body}],created:Math.floor(Date.now()/1e3)}}async edit(e,t){const r=this._client,s=new FormData,{model:n,style:o=this.models[n??"realistic"]}=e;return s.append("image",await P.toFile(e.image)),s.append("style_id",(o||29).toString()),s.append("prompt",e.prompt),s.append("negative_prompt",e.negative_prompt||""),s.append("strength",(e.strength||0).toString()),s.append("control",e.control||"openpose"),s.append("steps",(e.steps||30).toString()),s.append("cfg",(e.cfg||7.5).toString()),s.append("seed",(e.seed||R(1,1e6)).toString()),{data:[{binary:(await r.post(`/imagine/${r.apiType}/edits/remix`,{...t,body:{body:s,[Symbol.toStringTag]:"MultipartBody"},__binaryResponse:!0})).body}],created:Math.floor(Date.now()/1e3)}}async generate(e,t){const r=this._client,s=new FormData,{model:n,style:o=this.models[n??"imagine-v4"]}=e;s.append("style_id",(o||30).toString()),s.append("prompt",e.prompt),s.append("negative_prompt",e.negative_prompt||""),s.append("aspect_ratio",e.aspect_ratio||"1:1"),s.append("steps",(e.steps||30).toString()),s.append("cfg",(e.cfg||7.5).toString()),s.append("seed",(e.seed||R(1,1e6)).toString()),s.append("high_res_results",e.quality==="hd"?"1":"0");const i=await r.post(`/imagine/${r.apiType}/generations`,{...t,body:{body:s,[Symbol.toStringTag]:"MultipartBody"},__binaryResponse:!0});return{created:Math.floor(Date.now()/1e3),data:[{binary:i.body}]}}async upscale(e,t){const r=this._client,s=new FormData;s.append("image",await P.toFile(e.image));const n=await r.post(`/imagine/${r.apiType}/upscale`,{...t,body:{body:s,[Symbol.toStringTag]:"MultipartBody"},__binaryResponse:!0});return{created:Math.floor(Date.now()/1e3),data:[{binary:n.body}]}}async restoration(e,t){const r=this._client,s=new FormData;return s.append("image",await P.toFile(e.image)),s.append("mask",await P.toFile(e.mask)),s.append("style_id","1"),s.append("prompt",e.prompt),s.append("neg_prompt",e.negative_prompt||""),s.append("inpaint_strength",(e.strength||0).toString()),s.append("cfg",(e.cfg||7.5).toString()),{data:[{binary:(await r.post(`/imagine/${r.apiType}/generations/variations`,{...t,body:{body:s,[Symbol.toStringTag]:"MultipartBody"},__binaryResponse:!0})).body}],created:Math.floor(Date.now()/1e3)}}}class Je extends w.APIClient{constructor(e={}){const{apiKey:t=process.env.VYRO_API_KEY||"",apiType:r=process.env.VYRO_API_TYPE||"api",baseURL:s="https://api.vyro.ai/v1",timeout:n=3e4,fetch:o=globalThis.fetch,httpAgent:i=void 0,...c}=e;super({baseURL:s,timeout:n,fetch:o,httpAgent:i,...c}),this.images=new Ge(this),this._options=e,this.apiKey=t,this.apiType=r}authHeaders(){return{Authorization:`Bearer ${this.apiKey}`}}defaultHeaders(){return{...this.authHeaders(),...this._options.defaultHeaders}}defaultQuery(){return this._options.defaultQuery}}const We=Je,Qe={version:"0.0.1"};Object.defineProperty(exports,"APIConnectionError",{enumerable:!0,get:()=>u.APIConnectionError});Object.defineProperty(exports,"APIConnectionTimeoutError",{enumerable:!0,get:()=>u.APIConnectionTimeoutError});Object.defineProperty(exports,"APIError",{enumerable:!0,get:()=>u.APIError});Object.defineProperty(exports,"APIUserAbortError",{enumerable:!0,get:()=>u.APIUserAbortError});Object.defineProperty(exports,"AuthenticationError",{enumerable:!0,get:()=>u.AuthenticationError});Object.defineProperty(exports,"BadRequestError",{enumerable:!0,get:()=>u.BadRequestError});Object.defineProperty(exports,"ConflictError",{enumerable:!0,get:()=>u.ConflictError});Object.defineProperty(exports,"InternalServerError",{enumerable:!0,get:()=>u.InternalServerError});Object.defineProperty(exports,"NotFoundError",{enumerable:!0,get:()=>u.NotFoundError});exports.OpenAI=u;Object.defineProperty(exports,"OpenAIError",{enumerable:!0,get:()=>u.OpenAIError});Object.defineProperty(exports,"PermissionDeniedError",{enumerable:!0,get:()=>u.PermissionDeniedError});Object.defineProperty(exports,"RateLimitError",{enumerable:!0,get:()=>u.RateLimitError});Object.defineProperty(exports,"UnprocessableEntityError",{enumerable:!0,get:()=>u.UnprocessableEntityError});exports.APIResource=m;exports.ErnieAI=le;exports.GeminiAI=fe;exports.HunYuanAI=ye;exports.LineDecoder=k;exports.MinimaxAI=Ce;exports.QWenAI=He;exports.SSEDecoder=G;exports.SparkAI=Fe;exports.VYroAI=We;exports.castToError=ne;exports.default=Qe;exports.ensureArray=H;exports.iterMessages=z;exports.random=R;exports.readableStreamAsyncIterable=J;