react-chat-ai-widget
Version:
Enhance user experience with a smart widget that combines AI assistants and live chat. Automate support, stay available 24/7, and boost customer engagement effortlessly.
7 lines • 344 kB
JavaScript
(function(z,l){typeof exports=="object"&&typeof module<"u"?l(exports,require("react/jsx-runtime"),require("react"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom"],l):(z=typeof globalThis<"u"?globalThis:z||self,l(z["React-Chat-Widget"]={},z["react/jsx-runtime"],z.React,z.ReactDOM))})(this,function(z,l,w,vn){"use strict";var ud=Object.defineProperty;var md=(z,l,w)=>l in z?ud(z,l,{enumerable:!0,configurable:!0,writable:!0,value:w}):z[l]=w;var m=(z,l,w)=>md(z,typeof l!="symbol"?l+"":l,w);const mt=w.createContext(null),_n=({children:e,direction:t="left",onClose:n=()=>{},...a})=>{const i=w.useMemo(()=>({onClose:n,direction:t||"left",...a}),[a,t,n]);return l.jsx(mt.Provider,{value:i,children:e})},ee=()=>{const e=w.useContext(mt),t=w.useMemo(()=>e,[e]);if(t===null)throw new Error("useChatContext must be used within a `Context` provider");return t},xn=()=>{const e=w.useRef(null);return w.useEffect(()=>{if(e.current=document.getElementById("portal"),!e.current){const t=document.createElement("div");t.setAttribute("id","portal"),document.body.appendChild(t),e.current=document.getElementById("portal")}},[]),e.current},kn={bubble:"bottom-4 left-14",chatInterface:"bottom-16 left-24"},An={bubble:"right-6 bottom-6",chatInterface:"bottom-16 right-32"},Fe=e=>({right:An,left:kn})[e]??{bubble:"",chatInterface:""},In=({onClick:e})=>l.jsxs("svg",{role:"opener-chat",onClick:e,width:"35px","aria-label":"opener-chat",height:"35px",strokeWidth:"1.5",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",color:"#7e7e7e",children:[l.jsx("path",{d:"M9 9C9 5.49997 14.5 5.5 14.5 9C14.5 11.5 12 10.9999 12 13.9999",stroke:"#414141",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M12 18.01L12.01 17.9989",stroke:"#414141",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),l.jsx("path",{d:"M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 13.8214 2.48697 15.5291 3.33782 17L2.5 21.5L7 20.6622C8.47087 21.513 10.1786 22 12 22Z",stroke:"#414141",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})]}),ft=()=>l.jsx("div",{role:"loading-chat",children:l.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-slate-400",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[l.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),l.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]})}),Sn=({isOpen:e,direction:t,handleClick:n,isLoading:a,Loader:i})=>{const r=w.useMemo(()=>Fe(t),[t]),o=w.isValidElement(i);return l.jsxs("div",{className:`w-16 h-16 flex justify-center items-center rounded-full cursor-pointer
fixed ${r.bubble} -translate-x-1/2 bg-white shadow-lg
border border-gray-200 transition-all duration-300 ease-out hover:scale-110
`,"data-cy":"default-opener",tabIndex:0,role:"button","aria-label":"Open chat","aria-pressed":e,children:[a&&o&&l.jsx(l.Fragment,{children:i}),a&&!i&&l.jsx(ft,{}),!a&&l.jsx(In,{onClick:n})]})},Tn=w.lazy(()=>Promise.resolve().then(()=>od)),Cn=({direction:e="left",children:t,Loader:n,...a})=>{const[i,r]=w.useState(!1),[o,s]=w.useState(!1),d=w.useCallback(()=>{r(R=>!R)},[]),c=w.useCallback(()=>r(!1),[]),g=w.useMemo(()=>Fe(e),[e]),u=xn(),b=w.isValidElement(t),I=w.isValidElement(n),D=()=>(w.useEffect(()=>(s(!0),()=>s(!1)),[]),l.jsx(l.Fragment,{})),N=()=>!i||!u?null:l.jsx(w.Suspense,{fallback:l.jsx(D,{}),children:vn.createPortal(l.jsx(Tn,{isOpen:i}),u)}),O=()=>l.jsxs("div",{className:`w-16 h-16 flex justify-center items-center rounded-full cursor-pointer
fixed ${g.bubble} -translate-x-1/2 bg-white shadow-lg
border border-gray-200 transition-all duration-300 ease-out hover:scale-110
`,tabIndex:0,role:"button","aria-pressed":i,onClick:d,"data-testid":"open-chat-children","aria-label":"Open chat",children:[o&&I&&l.jsx(l.Fragment,{children:n}),o&&!n&&l.jsx(ft,{}),!o&&t]});return l.jsxs(l.Fragment,{children:[b?O():l.jsx(Sn,{Loader:n,isOpen:i,isLoading:o,direction:e,handleClick:d}),l.jsx(_n,{direction:e,onClose:c,...a,children:N()})]})},Ce={User:"user",Assistant:"assistant"},ht="Hi, I'm an AI assistant. How can I help you today? ",Ve=(e,t,n,a=null)=>({id:crypto.randomUUID(),role:e,content:t,error:a??null,isLoading:n??!1}),En=()=>Ve(Ce.Assistant,ht),Pn=e=>typeof e=="string"&&e.trim()!=="",$n=()=>{const[e,t]=w.useState([En()]);w.useEffect(()=>{localStorage.setItem("chat-messages",JSON.stringify(e))},[e]);const n=w.useCallback(async i=>{if(!Pn(i))return;const r=Ve(Ce.User,i);return t(o=>[...o,r]),r},[]),a=w.useCallback((i="",r)=>{const o=(r==null?void 0:r.isLoading)??!1,s=(r==null?void 0:r.error)??null,d=(r==null?void 0:r.errorType)??"general";t(c=>{const g=c[c.length-1];return g.content===ht?[...c]:!g||g.role!==Ce.Assistant?[...c,Ve(Ce.Assistant,i,o,s)]:[...c.slice(0,-1),{...g,content:g.content+i,isLoading:o,error:s,errorType:d}]})},[]);return w.useMemo(()=>({messages:e,addMessageUser:n,addMessageAssistant:a}),[e,n,a])};class gt{constructor(t,n,a,i,r,o){m(this,"apiKey");m(this,"model");m(this,"frecuency_penalty");m(this,"temperature");m(this,"max_tokens");m(this,"timeout");this.apiKey=t,this.model=n,this.frecuency_penalty=.5,this.temperature=i,this.max_tokens=r,this.timeout=o,this.frecuency_penalty=a}static builder(){return new Un}}class Un{constructor(){m(this,"apiKey","");m(this,"model","");m(this,"temperature",.7);m(this,"max_tokens",20);m(this,"frequency_penalty",.5);m(this,"timeout",3e4)}setApiKey(t){return this.apiKey=t,this}setFrequencyPenalty(t){return this.frequency_penalty=t,this}setModel(t){return this.model=t,this}setTemperature(t){return this.temperature=t,this}setMaxTokens(t){return this.max_tokens=t,this}setTimeout(t){return this.timeout=t,this}build(){if(!this.apiKey)throw new Error("API key is required");return new gt(this.apiKey,this.model,this.frequency_penalty,this.temperature,this.max_tokens,this.timeout)}}function jn(e){return typeof(e==null?void 0:e.model)=="string"&&typeof(e==null?void 0:e.temperature)=="number"&&typeof(e==null?void 0:e.max_tokens)=="number"&&typeof(e==null?void 0:e.timeout)=="number"&&typeof(e==null?void 0:e.frequency_penalty)=="number"}const He="https://huggingface.co",bt="https://router.huggingface.co",Nn="X-HF-Bill-To",yt={"black-forest-labs":{},cerebras:{},cohere:{},"fal-ai":{},"featherless-ai":{},"fireworks-ai":{},groq:{},"hf-inference":{},hyperbolic:{},nebius:{},novita:{},nscale:{},openai:{},ovhcloud:{},replicate:{},sambanova:{},together:{}};class Ke extends Error{constructor(t){super(t),this.name="InferenceClientError"}}class F extends Ke{constructor(t){super(t),this.name="InputError"}}class wt extends Ke{constructor(n,a,i){super(n);m(this,"httpRequest");m(this,"httpResponse");this.httpRequest={...a,...a.headers?{headers:{...a.headers,..."Authorization"in a.headers?{Authorization:"Bearer [redacted]"}:void 0}}:void 0},this.httpResponse=i}}class H extends wt{constructor(t,n,a){super(t,n,a),this.name="ProviderApiError"}}class ve extends wt{constructor(t,n,a){super(t,n,a),this.name="HubApiError"}}class v extends Ke{constructor(t){super(t),this.name="ProviderOutputError"}}function vt(e){return Array.isArray(e)?e:[e]}class J{constructor(t,n,a=!1){m(this,"provider");m(this,"baseUrl");m(this,"clientSideRoutingOnly");this.provider=t,this.baseUrl=n,this.clientSideRoutingOnly=a}makeBaseUrl(t){return t.authMethod!=="provider-key"?`${bt}/${this.provider}`:this.baseUrl}makeBody(t){return"data"in t.args&&t.args.data?t.args.data:JSON.stringify(this.preparePayload(t))}makeUrl(t){const n=this.makeBaseUrl(t),a=this.makeRoute(t).replace(/^\/+/,"");return`${n}/${a}`}prepareHeaders(t,n){const a={};return t.authMethod!=="none"&&(a.Authorization=`Bearer ${t.accessToken}`),n||(a["Content-Type"]="application/json"),a}}class Y extends J{constructor(t,n,a=!1){super(t,n,a)}makeRoute(){return"v1/chat/completions"}preparePayload(t){return{...t.args,model:t.model}}async getResponse(t){if(typeof t=="object"&&Array.isArray(t==null?void 0:t.choices)&&typeof(t==null?void 0:t.created)=="number"&&typeof(t==null?void 0:t.id)=="string"&&typeof(t==null?void 0:t.model)=="string"&&(t.system_fingerprint===void 0||t.system_fingerprint===null||typeof t.system_fingerprint=="string")&&typeof(t==null?void 0:t.usage)=="object")return t;throw new v("Expected ChatCompletionOutput")}}class de extends J{constructor(t,n,a=!1){super(t,n,a)}preparePayload(t){return{...t.args,model:t.model}}makeRoute(){return"v1/completions"}async getResponse(t){const n=vt(t);if(Array.isArray(n)&&n.length>0&&n.every(a=>typeof a=="object"&&!!a&&"generated_text"in a&&typeof a.generated_text=="string"))return n[0];throw new v("Expected Array<{generated_text: string}>")}}function G(e){if(globalThis.Buffer)return globalThis.Buffer.from(e).toString("base64");{const t=[];return e.forEach(n=>{t.push(String.fromCharCode(n))}),globalThis.btoa(t.join(""))}}function Mn(e,t){return Object.assign({},...t.map(n=>{if(e[n]!==void 0)return{[n]:e[n]}}))}function We(e,t){return e.includes(t)}function U(e,t){const n=Array.isArray(t)?t:[t],a=Object.keys(e).filter(i=>!We(n,i));return Mn(e,a)}const _t=["feature-extraction","sentence-similarity"];class j extends J{constructor(){super("hf-inference",`${bt}/hf-inference`)}preparePayload(t){return t.args}makeUrl(t){return t.model.startsWith("http://")||t.model.startsWith("https://")?t.model:super.makeUrl(t)}makeRoute(t){return t.task&&["feature-extraction","sentence-similarity"].includes(t.task)?`models/${t.model}/pipeline/${t.task}`:`models/${t.model}`}async getResponse(t){return t}}class Dn extends j{async getResponse(t,n,a,i){if(!t)throw new v("Received malformed response from HF-Inference text-to-image API: response is undefined");if(typeof t=="object"){if(i==="json")return{...t};if("data"in t&&Array.isArray(t.data)&&t.data[0].b64_json){const r=t.data[0].b64_json;return i==="url"?`data:image/jpeg;base64,${r}`:await(await fetch(`data:image/jpeg;base64,${r}`)).blob()}if("output"in t&&Array.isArray(t.output))return i==="url"?t.output[0]:await(await fetch(t.output[0])).blob()}if(t instanceof Blob){if(i==="url"||i==="json"){const r=await t.arrayBuffer().then(o=>Buffer.from(o).toString("base64"));return i==="url"?`data:image/jpeg;base64,${r}`:{output:`data:image/jpeg;base64,${r}`}}return t}throw new v("Received malformed response from HF-Inference text-to-image API: expected a Blob")}}class Rn extends j{makeUrl(t){let n;return t.model.startsWith("http://")||t.model.startsWith("https://")?n=t.model.trim():n=`${this.makeBaseUrl(t)}/models/${t.model}`,n=n.replace(/\/+$/,""),n.endsWith("/v1")?n+="/chat/completions":n.endsWith("/chat/completions")||(n+="/v1/chat/completions"),n}preparePayload(t){return{...t.args,model:t.model}}async getResponse(t){return t}}class Ln extends j{async getResponse(t){const n=vt(t);if(Array.isArray(n)&&n.every(a=>"generated_text"in a&&typeof(a==null?void 0:a.generated_text)=="string"))return n==null?void 0:n[0];throw new v("Received malformed response from HF-Inference text generation API: expected Array<{generated_text: string}>")}}class On extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n=="object"&&n!==null&&typeof n.label=="string"&&typeof n.score=="number"))return t;throw new v("Received malformed response from HF-Inference audio-classification API: expected Array<{label: string, score: number}> but received different format")}}class qn extends j{async getResponse(t){return t}async preparePayloadAsync(t){return"data"in t?t:{...U(t,"inputs"),data:t.inputs}}}class Bn extends j{async getResponse(t){if(!Array.isArray(t))throw new v("Received malformed response from HF-Inference audio-to-audio API: expected Array");if(!t.every(n=>typeof n=="object"&&n&&"label"in n&&typeof n.label=="string"&&"content-type"in n&&typeof n["content-type"]=="string"&&"blob"in n&&typeof n.blob=="string"))throw new v("Received malformed response from HF-Inference audio-to-audio API: expected Array<{label: string, audio: Blob}>");return t}}class Fn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n=="object"&&!!n&&typeof(n==null?void 0:n.answer)=="string"&&(typeof n.end=="number"||typeof n.end>"u")&&(typeof n.score=="number"||typeof n.score>"u")&&(typeof n.start=="number"||typeof n.start>"u")))return t[0];throw new v("Received malformed response from HF-Inference document-question-answering API: expected Array<{answer: string, end: number, score: number, start: number}>")}}class Vn extends j{async getResponse(t){const n=(a,i,r=0)=>r>i?!1:a.every(o=>Array.isArray(o))?a.every(o=>n(o,i,r+1)):a.every(o=>typeof o=="number");if(Array.isArray(t)&&n(t,3,0))return t;throw new v("Received malformed response from HF-Inference feature-extraction API: expected Array<number[][][] | number[][] | number[] | number>")}}class Hn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n.label=="string"&&typeof n.score=="number"))return t;throw new v("Received malformed response from HF-Inference image-classification API: expected Array<{label: string, score: number}>")}}class Kn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n.label=="string"&&typeof n.mask=="string"&&(n.score===void 0||typeof n.score=="number")))return t;throw new v("Received malformed response from HF-Inference image-segmentation API: expected Array<{label: string, mask: string, score: number}>")}async preparePayloadAsync(t){return{...t,inputs:G(new Uint8Array(t.inputs instanceof ArrayBuffer?t.inputs:await t.inputs.arrayBuffer()))}}}class Wn extends j{async getResponse(t){if(typeof(t==null?void 0:t.generated_text)!="string")throw new v("Received malformed response from HF-Inference image-to-text API: expected {generated_text: string}");return t}}class zn extends j{async preparePayloadAsync(t){return t.parameters?{...t,inputs:G(new Uint8Array(t.inputs instanceof ArrayBuffer?t.inputs:await t.inputs.arrayBuffer()))}:{...t,model:t.model,data:t.inputs}}async getResponse(t){if(t instanceof Blob)return t;throw new v("Received malformed response from HF-Inference image-to-image API: expected Blob")}}class Qn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n.label=="string"&&typeof n.score=="number"&&typeof n.box.xmin=="number"&&typeof n.box.ymin=="number"&&typeof n.box.xmax=="number"&&typeof n.box.ymax=="number"))return t;throw new v("Received malformed response from HF-Inference object-detection API: expected Array<{label: string, score: number, box: {xmin: number, ymin: number, xmax: number, ymax: number}}>")}}class Xn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n.label=="string"&&typeof n.score=="number"))return t;throw new v("Received malformed response from HF-Inference zero-shot-image-classification API: expected Array<{label: string, score: number}>")}}class Jn extends j{async getResponse(t){const n=t==null?void 0:t[0];if(Array.isArray(n)&&n.every(a=>typeof(a==null?void 0:a.label)=="string"&&typeof a.score=="number"))return n;throw new v("Received malformed response from HF-Inference text-classification API: expected Array<{label: string, score: number}>")}}class Yn extends j{async getResponse(t){if(Array.isArray(t)?t.every(n=>typeof n=="object"&&!!n&&typeof n.answer=="string"&&typeof n.end=="number"&&typeof n.score=="number"&&typeof n.start=="number"):typeof t=="object"&&t&&typeof t.answer=="string"&&typeof t.end=="number"&&typeof t.score=="number"&&typeof t.start=="number")return Array.isArray(t)?t[0]:t;throw new v("Received malformed response from HF-Inference question-answering API: expected Array<{answer: string, end: number, score: number, start: number}>")}}class Zn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n.score=="number"&&typeof n.sequence=="string"&&typeof n.token=="number"&&typeof n.token_str=="string"))return t;throw new v("Received malformed response from HF-Inference fill-mask API: expected Array<{score: number, sequence: string, token: number, token_str: string}>")}}class ze extends j{async getResponse(t){if(typeof t=="object"&&t!==null&&"labels"in t&&"scores"in t&&Array.isArray(t.labels)&&Array.isArray(t.scores)&&t.labels.length===t.scores.length&&t.labels.every(n=>typeof n=="string")&&t.scores.every(n=>typeof n=="number")){const n=t.scores;return t.labels.map((a,i)=>({label:a,score:n[i]}))}if(Array.isArray(t)&&t.every(ze.validateOutputElement))return t;throw new v("Received malformed response from HF-Inference zero-shot-classification API: expected Array<{label: string, score: number}>")}static validateOutputElement(t){return typeof t=="object"&&!!t&&"label"in t&&"score"in t&&typeof t.label=="string"&&typeof t.score=="number"}}class Gn extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n=="number"))return t;throw new v("Received malformed response from HF-Inference sentence-similarity API: expected Array<number>")}}class Ee extends j{static validate(t){return typeof t=="object"&&!!t&&"aggregator"in t&&typeof t.aggregator=="string"&&"answer"in t&&typeof t.answer=="string"&&"cells"in t&&Array.isArray(t.cells)&&t.cells.every(n=>typeof n=="string")&&"coordinates"in t&&Array.isArray(t.coordinates)&&t.coordinates.every(n=>Array.isArray(n)&&n.every(a=>typeof a=="number"))}async getResponse(t){if(Array.isArray(t)&&Array.isArray(t)?t.every(n=>Ee.validate(n)):Ee.validate(t))return Array.isArray(t)?t[0]:t;throw new v("Received malformed response from HF-Inference table-question-answering API: expected {aggregator: string, answer: string, cells: string[], coordinates: number[][]}")}}class ea extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n.end=="number"&&typeof n.entity_group=="string"&&typeof n.score=="number"&&typeof n.start=="number"&&typeof n.word=="string"))return t;throw new v("Received malformed response from HF-Inference token-classification API: expected Array<{end: number, entity_group: string, score: number, start: number, word: string}>")}}class ta extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof(n==null?void 0:n.translation_text)=="string"))return(t==null?void 0:t.length)===1?t==null?void 0:t[0]:t;throw new v("Received malformed response from HF-Inference translation API: expected Array<{translation_text: string}>")}}class na extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof(n==null?void 0:n.summary_text)=="string"))return t==null?void 0:t[0];throw new v("Received malformed response from HF-Inference summarization API: expected Array<{summary_text: string}>")}}class aa extends j{async getResponse(t){return t}}class ia extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n=="number"))return t;throw new v("Received malformed response from HF-Inference tabular-classification API: expected Array<number>")}}class ra extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n=="object"&&!!n&&typeof(n==null?void 0:n.answer)=="string"&&typeof n.score=="number"))return t[0];throw new v("Received malformed response from HF-Inference visual-question-answering API: expected Array<{answer: string, score: number}>")}}class oa extends j{async getResponse(t){if(Array.isArray(t)&&t.every(n=>typeof n=="number"))return t;throw new v("Received malformed response from HF-Inference tabular-regression API: expected Array<number>")}}class sa extends j{async getResponse(t){return t}}let la=console;function _e(){return la}const Qe=new Map;function ca(e,t){return t?Array.isArray(t)?t:Object.entries(t).map(([n,a])=>({provider:n,hfModelId:e,providerId:a.providerId,status:a.status,task:a.task,adapter:a.adapter,adapterWeightsPath:a.adapterWeightsPath})):[]}async function xt(e,t,n){var i;let a;if(Qe.has(e))a=Qe.get(e);else{const r=`${He}/api/models/${e}?expand[]=inferenceProviderMapping`,o=await((n==null?void 0:n.fetch)??fetch)(r,{headers:t!=null&&t.startsWith("hf_")?{Authorization:`Bearer ${t}`}:{}});if(!o.ok)if((i=o.headers.get("Content-Type"))!=null&&i.startsWith("application/json")){const d=await o.json();if("error"in d&&typeof d.error=="string")throw new ve(`Failed to fetch inference provider mapping for model ${e}: ${d.error}`,{url:r,method:"GET"},{requestId:o.headers.get("x-request-id")??"",status:o.status,body:d})}else throw new ve(`Failed to fetch inference provider mapping for model ${e}`,{url:r,method:"GET"},{requestId:o.headers.get("x-request-id")??"",status:o.status,body:await o.text()});let s=null;try{s=await o.json()}catch{throw new ve(`Failed to fetch inference provider mapping for model ${e}: malformed API response, invalid JSON`,{url:r,method:"GET"},{requestId:o.headers.get("x-request-id")??"",status:o.status,body:await o.text()})}if(!(s!=null&&s.inferenceProviderMapping))throw new ve(`We have not been able to find inference provider information for model ${e}.`,{url:r,method:"GET"},{requestId:o.headers.get("x-request-id")??"",status:o.status,body:await o.text()});a=ca(e,s.inferenceProviderMapping),Qe.set(e,a)}return a}async function da(e,t){const n=_e();if(yt[e.provider][e.modelId])return yt[e.provider][e.modelId];const i=(await xt(e.modelId,e.accessToken,t)).find(r=>r.provider===e.provider);if(i){const r=e.provider==="hf-inference"&&We(_t,e.task)?_t:[e.task];if(!We(r,i.task))throw new F(`Model ${e.modelId} is not supported for task ${e.task} and provider ${e.provider}. Supported task: ${i.task}.`);return i.status==="staging"&&n.warn(`Model ${e.modelId} is in staging mode for provider ${e.provider}. Meant for test purposes only.`),i}return null}async function C(e,t,n){var i;const a=_e();if(n){if(e)throw new F("Specifying both endpointUrl and provider is not supported.");return"hf-inference"}if(e||(a.log("Defaulting to 'auto' which will select the first provider available for the model, sorted by the user's order in https://hf.co/settings/inference-providers."),e="auto"),e==="auto"){if(!t)throw new F("Specifying a model is required when provider is 'auto'");e=(i=(await xt(t))[0])==null?void 0:i.provider,a.log("Auto selected provider:",e)}if(!e)throw new F(`No Inference Provider available for model ${t}.`);return e}function Xe(e){return new Promise(t=>{setTimeout(()=>t(),e)})}const pa="https://api.us1.bfl.ai";class ua extends J{constructor(){super("black-forest-labs",pa)}preparePayload(t){return{...U(t.args,["inputs","parameters"]),...t.args.parameters,prompt:t.args.inputs}}prepareHeaders(t,n){const a={Authorization:t.authMethod!=="provider-key"?`Bearer ${t.accessToken}`:`X-Key ${t.accessToken}`};return n||(a["Content-Type"]="application/json"),a}makeRoute(t){if(!t)throw new F("Params are required");return`/v1/${t.model}`}async getResponse(t,n,a,i){const r=_e(),o=new URL(t.polling_url);for(let s=0;s<5;s++){await Xe(1e3),r.debug(`Polling Black Forest Labs API for the result... ${s+1}/5`),o.searchParams.set("attempt",s.toString(10));const d=await fetch(o,{headers:{"Content-Type":"application/json"}});if(!d.ok)throw new H("Failed to fetch result from black forest labs API",{url:o.toString(),method:"GET",headers:{"Content-Type":"application/json"}},{requestId:d.headers.get("x-request-id")??"",status:d.status,body:await d.text()});const c=await d.json();if(typeof c=="object"&&c&&"status"in c&&typeof c.status=="string"&&c.status==="Ready"&&"result"in c&&typeof c.result=="object"&&c.result&&"sample"in c.result&&typeof c.result.sample=="string")return i==="json"?c.result:i==="url"?c.result.sample:await(await fetch(c.result.sample)).blob()}throw new v("Timed out while waiting for the result from black forest labs API - aborting after 5 attempts")}}class ma extends Y{constructor(){super("cerebras","https://api.cerebras.ai")}}class fa extends Y{constructor(){super("cohere","https://api.cohere.com")}makeRoute(){return"/compatibility/v1/chat/completions"}}function pe(e){return/^http(s?):/.test(e)||e.startsWith("/")}const kt=["audio/mpeg","audio/mp4","audio/wav","audio/x-wav"];class Pe extends J{constructor(t){super("fal-ai",t||"https://fal.run")}preparePayload(t){return t.args}makeRoute(t){return`/${t.model}`}prepareHeaders(t,n){const a={Authorization:t.authMethod!=="provider-key"?`Bearer ${t.accessToken}`:`Key ${t.accessToken}`};return n||(a["Content-Type"]="application/json"),a}}class $e extends Pe{async getResponseFromQueueApi(t,n,a){if(!n||!a)throw new F(`URL and headers are required for ${this.task} task`);if(!t.request_id)throw new v(`Received malformed response from Fal.ai ${this.task} API: no request ID found in the response`);let r=t.status;const o=new URL(n),s=`${o.protocol}//${o.host}${o.host==="router.huggingface.co"?"/fal-ai":""}`,d=new URL(t.response_url).pathname,c=o.search,g=`${s}${d}/status${c}`,u=`${s}${d}${c}`;for(;r!=="COMPLETED";){await Xe(500);const D=await fetch(g,{headers:a});if(!D.ok)throw new H("Failed to fetch response status from fal-ai API",{url:g,method:"GET"},{requestId:D.headers.get("x-request-id")??"",status:D.status,body:await D.text()});try{r=(await D.json()).status}catch{throw new v("Failed to parse status response from fal-ai API: received malformed response")}}const b=await fetch(u,{headers:a});let I;try{I=await b.json()}catch{throw new v("Failed to parse result response from fal-ai API: received malformed response")}return I}}function At(e,t){return`${He}/${e}/resolve/main/${t}`}class ha extends Pe{preparePayload(t){var a;const n={...U(t.args,["inputs","parameters"]),...t.args.parameters,sync_mode:!0,prompt:t.args.inputs};return((a=t.mapping)==null?void 0:a.adapter)==="lora"&&t.mapping.adapterWeightsPath&&(n.loras=[{path:At(t.mapping.hfModelId,t.mapping.adapterWeightsPath),scale:1}],t.mapping.providerId==="fal-ai/lora"&&(n.model_name="stabilityai/stable-diffusion-xl-base-1.0")),n}async getResponse(t,n,a,i){if(typeof t=="object"&&"images"in t&&Array.isArray(t.images)&&t.images.length>0&&"url"in t.images[0]&&typeof t.images[0].url=="string")return i==="json"?{...t}:i==="url"?t.images[0].url:await(await fetch(t.images[0].url)).blob();throw new v("Received malformed response from Fal.ai text-to-image API")}}class ga extends $e{constructor(){super("https://queue.fal.run");m(this,"task");this.task="image-to-image"}makeRoute(n){return n.authMethod!=="provider-key"?`/${n.model}?_subdomain=queue`:`/${n.model}`}preparePayload(n){var i;const a=n.args;return((i=n.mapping)==null?void 0:i.adapter)==="lora"&&n.mapping.adapterWeightsPath&&(a.loras=[{path:At(n.mapping.hfModelId,n.mapping.adapterWeightsPath),scale:1}]),a}async preparePayloadAsync(n){const a=n.inputs instanceof Blob?n.inputs.type:"image/png";return{...U(n,["inputs","parameters"]),image_url:`data:${a};base64,${G(new Uint8Array(n.inputs instanceof ArrayBuffer?n.inputs:await n.inputs.arrayBuffer()))}`,...n.parameters,...n}}async getResponse(n,a,i){const r=await this.getResponseFromQueueApi(n,a,i);if(typeof r=="object"&&r&&"images"in r&&Array.isArray(r.images)&&r.images.length>0&&typeof r.images[0]=="object"&&r.images[0]&&"url"in r.images[0]&&typeof r.images[0].url=="string"&&pe(r.images[0].url))return await(await fetch(r.images[0].url)).blob();throw new v(`Received malformed response from Fal.ai image-to-image API: expected { images: Array<{ url: string }> } result format, got instead: ${JSON.stringify(r)}`)}}class ba extends $e{constructor(){super("https://queue.fal.run");m(this,"task");this.task="text-to-video"}makeRoute(n){return n.authMethod!=="provider-key"?`/${n.model}?_subdomain=queue`:`/${n.model}`}preparePayload(n){return{...U(n.args,["inputs","parameters"]),...n.args.parameters,prompt:n.args.inputs}}async getResponse(n,a,i){const r=await this.getResponseFromQueueApi(n,a,i);if(typeof r=="object"&&r&&"video"in r&&typeof r.video=="object"&&r.video&&"url"in r.video&&typeof r.video.url=="string"&&pe(r.video.url))return await(await fetch(r.video.url)).blob();throw new v(`Received malformed response from Fal.ai text-to-video API: expected { video: { url: string } } result format, got instead: ${JSON.stringify(r)}`)}}class ya extends $e{constructor(){super("https://queue.fal.run");m(this,"task");this.task="image-to-video"}makeRoute(n){return n.authMethod!=="provider-key"?`/${n.model}?_subdomain=queue`:`/${n.model}`}preparePayload(n){return{...U(n.args,["inputs","parameters"]),...n.args.parameters,image_url:n.args.image_url}}async preparePayloadAsync(n){const a=n.inputs instanceof Blob?n.inputs.type:"image/png";return{...U(n,["inputs","parameters"]),image_url:`data:${a};base64,${G(new Uint8Array(n.inputs instanceof ArrayBuffer?n.inputs:await n.inputs.arrayBuffer()))}`,...n.parameters,...n}}async getResponse(n,a,i){const r=await this.getResponseFromQueueApi(n,a,i);if(typeof r=="object"&&r!==null&&"video"in r&&typeof r.video=="object"&&r.video!==null&&"url"in r.video&&typeof r.video.url=="string"&&"url"in r.video&&pe(r.video.url))return await(await fetch(r.video.url)).blob();throw new v(`Received malformed response from Fal.ai image‑to‑video API: expected { video: { url: string } }, got: ${JSON.stringify(r)}`)}}class wa extends Pe{prepareHeaders(t,n){const a=super.prepareHeaders(t,n);return a["Content-Type"]="application/json",a}async getResponse(t){const n=t;if(typeof(n==null?void 0:n.text)!="string")throw new v(`Received malformed response from Fal.ai Automatic Speech Recognition API: expected { text: string } format, got instead: ${JSON.stringify(t)}`);return{text:n.text}}async preparePayloadAsync(t){const n="data"in t&&t.data instanceof Blob?t.data:"inputs"in t?t.inputs:void 0,a=n==null?void 0:n.type;if(!a)throw new F("Unable to determine the input's content-type. Make sure your are passing a Blob when using provider fal-ai.");if(!kt.includes(a))throw new F(`Provider fal-ai does not support blob type ${a} - supported content types are: ${kt.join(", ")}`);const i=G(new Uint8Array(await n.arrayBuffer()));return{..."data"in t?U(t,"data"):U(t,"inputs"),audio_url:`data:${a};base64,${i}`}}}class va extends Pe{preparePayload(t){return{...U(t.args,["inputs","parameters"]),...t.args.parameters,text:t.args.inputs}}async getResponse(t){var i;const n=t;if(typeof((i=n==null?void 0:n.audio)==null?void 0:i.url)!="string")throw new v(`Received malformed response from Fal.ai Text-to-Speech API: expected { audio: { url: string } } format, got instead: ${JSON.stringify(t)}`);const a=await fetch(n.audio.url);if(!a.ok)throw new H(`Failed to fetch audio from ${n.audio.url}: ${a.statusText}`,{url:n.audio.url,method:"GET",headers:{"Content-Type":"application/json"}},{requestId:a.headers.get("x-request-id")??"",status:a.status,body:await a.text()});try{return await a.blob()}catch(r){throw new H(`Failed to fetch audio from ${n.audio.url}: ${r instanceof Error?r.message:String(r)}`,{url:n.audio.url,method:"GET",headers:{"Content-Type":"application/json"}},{requestId:a.headers.get("x-request-id")??"",status:a.status,body:await a.text()})}}}class _a extends $e{constructor(){super("https://queue.fal.run");m(this,"task");this.task="image-segmentation"}makeRoute(n){return n.authMethod!=="provider-key"?`/${n.model}?_subdomain=queue`:`/${n.model}`}preparePayload(n){return{...U(n.args,["inputs","parameters"]),...n.args.parameters,sync_mode:!0}}async preparePayloadAsync(n){const a="data"in n&&n.data instanceof Blob?n.data:"inputs"in n?n.inputs:void 0,i=a instanceof Blob?a.type:"image/png",r=G(new Uint8Array(a instanceof ArrayBuffer?a:await a.arrayBuffer()));return{...U(n,["inputs","parameters","data"]),...n.parameters,...n,image_url:`data:${i};base64,${r}`,sync_mode:!0}}async getResponse(n,a,i){const r=await this.getResponseFromQueueApi(n,a,i);if(typeof r=="object"&&r!==null&&"image"in r&&typeof r.image=="object"&&r.image!==null&&"url"in r.image&&typeof r.image.url=="string"){const o=await fetch(r.image.url);if(!o.ok)throw new H(`Failed to fetch segmentation mask from ${r.image.url}`,{url:r.image.url,method:"GET"},{requestId:o.headers.get("x-request-id")??"",status:o.status,body:await o.text()});const d=await(await o.blob()).arrayBuffer();return[{label:"mask",score:1,mask:G(new Uint8Array(d))}]}throw new v(`Received malformed response from Fal.ai image-segmentation API: expected { image: { url: string } } format, got instead: ${JSON.stringify(n)}`)}}const It="https://api.featherless.ai";class xa extends Y{constructor(){super("featherless-ai",It)}}class ka extends de{constructor(){super("featherless-ai",It)}preparePayload(t){return{model:t.model,...U(t.args,["inputs","parameters"]),...t.args.parameters?{max_tokens:t.args.parameters.max_new_tokens,...U(t.args.parameters,"max_new_tokens")}:void 0,prompt:t.args.inputs}}async getResponse(t){if(typeof t=="object"&&"choices"in t&&Array.isArray(t==null?void 0:t.choices)&&typeof(t==null?void 0:t.model)=="string")return{generated_text:t.choices[0].text};throw new v("Received malformed response from Featherless AI text generation API")}}class Aa extends Y{constructor(){super("fireworks-ai","https://api.fireworks.ai")}makeRoute(){return"/inference/v1/chat/completions"}}const St="https://api.groq.com";class Ia extends de{constructor(){super("groq",St)}makeRoute(){return"/openai/v1/chat/completions"}}class Sa extends Y{constructor(){super("groq",St)}makeRoute(){return"/openai/v1/chat/completions"}}const Je="https://api.hyperbolic.xyz";class Ta extends Y{constructor(){super("hyperbolic",Je)}}class Ca extends de{constructor(){super("hyperbolic",Je)}makeRoute(){return"v1/chat/completions"}preparePayload(t){return{messages:[{content:t.args.inputs,role:"user"}],...t.args.parameters?{max_tokens:t.args.parameters.max_new_tokens,...U(t.args.parameters,"max_new_tokens")}:void 0,...U(t.args,["inputs","parameters"]),model:t.model}}async getResponse(t){if(typeof t=="object"&&"choices"in t&&Array.isArray(t==null?void 0:t.choices)&&typeof(t==null?void 0:t.model)=="string")return{generated_text:t.choices[0].message.content};throw new v("Received malformed response from Hyperbolic text generation API")}}class Ea extends J{constructor(){super("hyperbolic",Je)}makeRoute(t){return"/v1/images/generations"}preparePayload(t){return{...U(t.args,["inputs","parameters"]),...t.args.parameters,prompt:t.args.inputs,model_name:t.model}}async getResponse(t,n,a,i){if(typeof t=="object"&&"images"in t&&Array.isArray(t.images)&&t.images[0]&&typeof t.images[0].image=="string")return i==="json"?{...t}:i==="url"?`data:image/jpeg;base64,${t.images[0].image}`:fetch(`data:image/jpeg;base64,${t.images[0].image}`).then(r=>r.blob());throw new v("Received malformed response from Hyperbolic text-to-image API")}}const Ue="https://api.studio.nebius.ai";class Pa extends Y{constructor(){super("nebius",Ue)}preparePayload(t){var i;const n=super.preparePayload(t),a=t.args.response_format;return(a==null?void 0:a.type)==="json_schema"&&((i=a.json_schema)!=null&&i.schema)&&(n.guided_json=a.json_schema.schema),n}}class $a extends de{constructor(){super("nebius",Ue)}preparePayload(t){return{...t.args,model:t.model,prompt:t.args.inputs}}async getResponse(t){var n;if(typeof t=="object"&&"choices"in t&&Array.isArray(t==null?void 0:t.choices)&&t.choices.length>0&&typeof((n=t.choices[0])==null?void 0:n.text)=="string")return{generated_text:t.choices[0].text};throw new v("Received malformed response from Nebius text generation API")}}class Ua extends J{constructor(){super("nebius",Ue)}preparePayload(t){return{...U(t.args,["inputs","parameters"]),...t.args.parameters,response_format:"b64_json",prompt:t.args.inputs,model:t.model}}makeRoute(){return"v1/images/generations"}async getResponse(t,n,a,i){if(typeof t=="object"&&"data"in t&&Array.isArray(t.data)&&t.data.length>0&&"b64_json"in t.data[0]&&typeof t.data[0].b64_json=="string"){if(i==="json")return{...t};const r=t.data[0].b64_json;return i==="url"?`data:image/jpeg;base64,${r}`:fetch(`data:image/jpeg;base64,${r}`).then(o=>o.blob())}throw new v("Received malformed response from Nebius text-to-image API")}}class ja extends J{constructor(){super("nebius",Ue)}preparePayload(t){return{input:t.args.inputs,model:t.model}}makeRoute(){return"v1/embeddings"}async getResponse(t){return t.data.map(n=>n.embedding)}}const Ye="https://api.novita.ai";class Na extends de{constructor(){super("novita",Ye)}makeRoute(){return"/v3/openai/chat/completions"}}class Ma extends Y{constructor(){super("novita",Ye)}makeRoute(){return"/v3/openai/chat/completions"}}class Da extends J{constructor(){super("novita",Ye)}makeRoute(t){return`/v3/async/${t.model}`}preparePayload(t){const{num_inference_steps:n,...a}=t.args.parameters??{};return{...U(t.args,["inputs","parameters"]),...a,steps:n,prompt:t.args.inputs}}async getResponse(t,n,a){if(!n||!a)throw new F("URL and headers are required for text-to-video task");const i=t.task_id;if(!i)throw new v("Received malformed response from Novita text-to-video API: no task ID found in the response");const r=new URL(n),s=`${`${r.protocol}//${r.host}${r.host==="router.huggingface.co"?"/novita":""}`}/v3/async/task-result?task_id=${i}`;let d="",c;for(;d!=="TASK_STATUS_SUCCEED"&&d!=="TASK_STATUS_FAILED";){await Xe(500);const g=await fetch(s,{headers:a});if(!g.ok)throw new H("Failed to fetch task result",{url:s,method:"GET",headers:a},{requestId:g.headers.get("x-request-id")??"",status:g.status,body:await g.text()});try{if(c=await g.json(),c&&typeof c=="object"&&"task"in c&&c.task&&typeof c.task=="object"&&"status"in c.task&&typeof c.task.status=="string")d=c.task.status;else throw new v("Received malformed response from Novita text-to-video API: failed to get task status")}catch{throw new v("Received malformed response from Novita text-to-video API: failed to parse task result")}}if(d==="TASK_STATUS_FAILED")throw new v("Novita text-to-video task failed");if(typeof c=="object"&&c&&"videos"in c&&typeof c.videos=="object"&&c.videos&&Array.isArray(c.videos)&&c.videos.length>0&&"video_url"in c.videos[0]&&typeof c.videos[0].video_url=="string"&&pe(c.videos[0].video_url))return await(await fetch(c.videos[0].video_url)).blob();throw new v(`Received malformed response from Novita text-to-video API: expected { videos: [{ video_url: string }] } format, got instead: ${JSON.stringify(c)}`)}}const Tt="https://inference.api.nscale.com";class Ra extends Y{constructor(){super("nscale",Tt)}}class La extends J{constructor(){super("nscale",Tt)}preparePayload(t){return{...U(t.args,["inputs","parameters"]),...t.args.parameters,response_format:"b64_json",prompt:t.args.inputs,model:t.model}}makeRoute(){return"v1/images/generations"}async getResponse(t,n,a,i){if(typeof t=="object"&&"data"in t&&Array.isArray(t.data)&&t.data.length>0&&"b64_json"in t.data[0]&&typeof t.data[0].b64_json=="string"){if(i==="json")return{...t};const r=t.data[0].b64_json;return i==="url"?`data:image/jpeg;base64,${r}`:fetch(`data:image/jpeg;base64,${r}`).then(o=>o.blob())}throw new v("Received malformed response from Nscale text-to-image API")}}const Oa="https://api.openai.com";class qa extends Y{constructor(){super("openai",Oa,!0)}}const Ct="https://oai.endpoints.kepler.ai.cloud.ovh.net";class Ba extends Y{constructor(){super("ovhcloud",Ct)}}class Fa extends de{constructor(){super("ovhcloud",Ct)}preparePayload(t){return{model:t.model,...U(t.args,["inputs","parameters"]),...t.args.parameters?{max_tokens:t.args.parameters.max_new_tokens,...U(t.args.parameters,"max_new_tokens")}:void 0,prompt:t.args.inputs}}async getResponse(t){if(typeof t=="object"&&"choices"in t&&Array.isArray(t==null?void 0:t.choices)&&typeof(t==null?void 0:t.model)=="string")return{generated_text:t.choices[0].text};throw new v("Received malformed response from OVHcloud text generation API")}}class je extends J{constructor(t){super("replicate",t||"https://api.replicate.com")}makeRoute(t){return t.model.includes(":")?"v1/predictions":`v1/models/${t.model}/predictions`}preparePayload(t){return{input:{...U(t.args,["inputs","parameters"]),...t.args.parameters,prompt:t.args.inputs},version:t.model.includes(":")?t.model.split(":")[1]:void 0}}prepareHeaders(t,n){const a={Authorization:`Bearer ${t.accessToken}`,Prefer:"wait"};return n||(a["Content-Type"]="application/json"),a}makeUrl(t){const n=this.makeBaseUrl(t);return t.model.includes(":")?`${n}/v1/predictions`:`${n}/v1/models/${t.model}/predictions`}}class Va extends je{preparePayload(t){var n;return{input:{...U(t.args,["inputs","parameters"]),...t.args.parameters,prompt:t.args.inputs,lora_weights:((n=t.mapping)==null?void 0:n.adapter)==="lora"&&t.mapping.adapterWeightsPath?`https://huggingface.co/${t.mapping.hfModelId}`:void 0},version:t.model.includes(":")?t.model.split(":")[1]:void 0}}async getResponse(t,n,a,i){if(typeof t=="object"&&"output"in t&&Array.isArray(t.output)&&t.output.length>0&&typeof t.output[0]=="string")return i==="json"?{...t}:i==="url"?t.output[0]:await(await fetch(t.output[0])).blob();throw new v("Received malformed response from Replicate text-to-image API")}}class Ha extends je{preparePayload(t){const n=super.preparePayload(t),a=n.input;if(typeof a=="object"&&a!==null&&"prompt"in a){const i=a;i.text=i.prompt,delete i.prompt}return n}async getResponse(t){if(t instanceof Blob)return t;if(t&&typeof t=="object"&&"output"in t){if(typeof t.output=="string")return await(await fetch(t.output)).blob();if(Array.isArray(t.output))return await(await fetch(t.output[0])).blob()}throw new v("Received malformed response from Replicate text-to-speech API")}}class Ka extends je{async getResponse(t){if(typeof t=="object"&&t&&"output"in t&&typeof t.output=="string"&&pe(t.output))return await(await fetch(t.output)).blob();throw new v("Received malformed response from Replicate text-to-video API")}}class Wa extends je{preparePayload(t){var n;return{input:{...U(t.args,["inputs","parameters"]),...t.args.parameters,input_image:t.args.inputs,lora_weights:((n=t.mapping)==null?void 0:n.adapter)==="lora"&&t.mapping.adapterWeightsPath?`https://huggingface.co/${t.mapping.hfModelId}`:void 0},version:t.model.includes(":")?t.model.split(":")[1]:void 0}}async preparePayloadAsync(t){const{inputs:n,...a}=t,i=new Uint8Array(await n.arrayBuffer()),r=G(i),o=`data:${n.type||"image/jpeg"};base64,${r}`;return{...a,inputs:o}}async getResponse(t){if(typeof t=="object"&&t&&"output"in t&&Array.isArray(t.output)&&t.output.length>0&&typeof t.output[0]=="string")return await(await fetch(t.output[0])).blob();if(typeof t=="object"&&t&&"output"in t&&typeof t.output=="string"&&pe(t.output))return await(await fetch(t.output)).blob();throw new v("Received malformed response from Replicate image-to-image API")}}class za extends Y{constructor(){super("sambanova","https://api.sambanova.ai")}preparePayload(t){const n=t.args.response_format;return(n==null?void 0:n.type)==="json_schema"&&n.json_schema&&(n.json_schema.strict??!0)&&(n.json_schema.strict=!1),super.preparePayload(t)}}class Qa extends J{constructor(){super("sambanova","https://api.sambanova.ai")}makeRoute(){return"/v1/embeddings"}async getResponse(t){if(typeof t=="object"&&"data"in t&&Array.isArray(t.data))return t.data.map(n=>n.embedding);throw new v("Received malformed response from Sambanova feature-extraction (embeddings) API")}preparePayload(t){return{model:t.model,input:t.args.inputs,...t.args}}}const Ze="https://api.together.xyz";class Xa extends Y{constructor(){super("together",Ze)}preparePayload(t){var i;const n=super.preparePayload(t),a=n.response_format;return(a==null?void 0:a.type)==="json_schema"&&((i=a==null?void 0:a.json_schema)!=null&&i.schema)&&(n.response_format={type:"json_schema",schema:a.json_schema.schema}),n}}class Ja extends de{constructor(){super("together",Ze)}preparePayload(t){return{model:t.model,...t.args,prompt:t.args.inputs}}async getResponse(t){if(typeof t=="object"&&"choices"in t&&Array.isArray(t==null?void 0:t.choices)&&typeof(t==null?void 0:t.model)=="string")return{generated_text:t.choices[0].text};throw new v("Received malformed response from Together text generation API")}}class Ya extends J{constructor(){super("together",Ze)}makeRoute(){return"v1/images/generations"}preparePayload(t){return{...U(t.args,["inputs","parameters"]),...t.args.parameters,prompt:t.args.inputs,response_format:"base64",model:t.model}}async getResponse(t,n,a,i){if(typeof t=="object"&&"data"in t&&Array.isArray(t.data)&&t.data.length>0&&"b64_json"in t.data[0]&&typeof t.data[0].b64_json=="string"){if(i==="json")return{...t};const r=t.data[0].b64_json;return i==="url"?`data:image/jpeg;base64,${r}`:fetch(`data:image/jpeg;base64,${r}`).then(o=>o.blob())}throw new v("Received malformed response from Together text-to-image API")}}const Ge={"black-forest-labs":{"text-to-image":new ua},cerebras:{conversational:new ma},cohere:{conversational:new fa},"fal-ai":{"text-to-image":new ha,"text-to-speech":new va,"text-to-video":new ba,"image-to-image":new ga,"automatic-speech-recognition":new wa,"image-segmentation":new _a,"image-to-video":new ya},"featherless-ai":{conversational:new xa,"text-generation":new ka},"hf-inference":{"text-to-image":new Dn,conversational:new Rn,"text-generation":new Ln,"text-classification":new Jn,"question-answering":new Yn,"audio-classification":new On,"automatic-speech-recognition":new qn,"fill-mask":new Zn,"feature-extraction":new Vn,"image-classification":new Hn,"image-segmentation":new Kn,"document-question-answering":new Fn,"image-to-text":new Wn,"object-detection":new Qn,"audio-to-audio":new Bn,"zero-shot-image-classification":new Xn,"zero-shot-classification":new ze,"image-to-image":new zn,"sentence-similarity":new Gn,"table-question-answering":new Ee,"tabular-classification":new ia,"text-to-speech":new aa,"token-classification":new ea,translation:new ta,summarization:new na,"visual-question-answering":new ra,"tabular-regression":new oa,"text-to-audio":new sa},"fireworks-ai":{conversational:new Aa},groq:{conversational:new Sa,"text-generation":new Ia},hyperbolic:{"text-to-image":new Ea,conversational:new Ta,"text-generation":new Ca},nebius:{"text-to-image":new Ua,conversational:new Pa,"text-generation":new $a,"feature-extraction":new ja},novita:{conversational:new Ma,"text-generation":new Na,"text-to-video":new Da},nscale:{"text-to-image":new La,conversational:new Ra},openai:{conversational:new qa},ovhcloud:{conversational:new Ba,"text-generation":new Fa},replicate:{"text-to-image":new Va,"text-to-speech":new Ha,"text-to-video":new Ka,"image-to-image":new Wa},sambanova:{conversational:new za,"feature-extraction":new Qa},together:{"text-to-image":new Ya,conversational:new Xa,"text-generation":new Ja}};function E(e,t){if(e==="hf-inference"&&!t||e==="auto")return new j;if(!t)throw new F("you need to provide a task name when using an external provider, e.g. 'text-to-image'");if(!(e in Ge))throw new F(`Provider '${e}' not supported. Available providers: ${Object.keys(Ge)}`);const n=Ge[e];if(!n||!(t in n))throw new F(`Task '${t}' not supported for provider '${e}'. Available tasks: ${Object.keys(n??{})}`);return n[t]}const Za="4.6.1",Ga="@huggingface/inference";let et=null;async function ue(e,t,n){const{model:a}=e,i=t.provider,{task:r}=n??{};if(e.endpointUrl&&i!=="hf-inference")throw new F("Cannot use endpointUrl with a third-party provider.");if(a&&pe(a))throw new F("Model URLs are no longer supported. Use endpointUrl instead.");if(e.endpointUrl)return Et(a??e.endpointUrl,t,e,void 0,n);if(!a&&!r)throw new F("No model provided, and no task has been specified.");const o=a??await ei(r);if(t.clientSideRoutingOnly&&!a)throw new F(`Provider ${i} requires a model ID to be passed directly.`);const s=t.clientSideRoutingOnly?{provider:i,providerId:ni(a,i),hfModelId:a,status:"live",task:r}:await da({modelId:o,task:r,provider:i,accessToken:e.accessToken},{fetch:n==null?void 0:n.fetch});if(!s)throw new F(`We have not been able to find inference provider information for model ${o}.`);return Et(s.providerId,t,e,s,n)}function Et(e,t,n,a,i){const{accessToken:r,endpointUrl:o,provider:s,model:d,...c}=n,g=t.provider,{includeCredentials:u,task:b,signal:I,billTo:D}=i??{},N=(()=>{if(t.clientSideRoutingOnly&&r&&r.startsWith("hf_"))throw new F(`Provider ${g} is closed-source and does not support HF tokens.`);return r?r.startsWith("hf_")?"hf-token":"provider-key":u==="include"?"credentials-include":"none"})(),O=o??e,R=t.makeUrl({authMethod:N,model:O,task:b}),le=t.prepareHeaders({accessToken:r,authMethod:N},"data"in n&&!!n.data);D&&(le[Nn]=D);const Le=[`${Ga}/${Za}`,typeof navigator<"u"?navigator.userAgent:void 0].filter(ut=>ut!==void 0).join(" ");le["User-Agent"]=Le;const Te=t.makeBody({args:c,model:e,task:b,mapping:a});let we;typeof u=="string"?we=u:u===!0&&(we="include");const Oe={headers:le,method:"POST",body:Te,...we?{credentials:we}:void 0,signal:I};return{url:R,info:Oe}}async function ei(e){et||(et=await ti());const t=et[e];if(((t==null?void 0:t.models.length)??0)<=0)throw new F(`No default model defined for task ${e}, please define the model explicitly.`);return t.models[0].id}async function ti(){const e=`${He}/api/tasks`,t=await fetch(e);if(!t.ok)throw new ve("Failed to load tasks definitions from Hugging Face Hub.",{url:e,method:"GET"},{requestId:t.headers.get("x-request-id")??"",status:t.status,body:await t.text()});return await t.json()}function ni(e,t){if(!e.startsWith(`${t}/`))throw new F(`Models from ${t} must be prefixed by "${t}/". Got "${e}".`);return e.slice(t.length+1)}function