@adaline/azure
Version:
Adaline Azure
11 lines (10 loc) • 75.8 kB
JavaScript
import { z as z$1 } from 'zod';
var we=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),qn=e=>{throw TypeError(e)};var zn=function(e,t){this[0]=e,this[1]=t;};var Et=e=>{var t=e[we("asyncIterator")],n=!1,s,i={};return t==null?(t=e[we("iterator")](),s=l=>i[l]=r=>t[l](r)):(t=t.call(e),s=l=>i[l]=r=>{if(n){if(n=!1,l==="throw")throw r;return r}return n=!0,{done:!1,value:new zn(new Promise(d=>{var c=t[l](r);c instanceof Object||qn("Object expected"),d(c);}),1)}}),i[we("iterator")]=()=>i,s("next"),"throw"in t?s("throw"):i.throw=l=>{throw l},"return"in t&&s("return"),i};var P=z$1.object({apiKey:z$1.string().min(1),deploymentId:z$1.string().min(1),resourceName:z$1.string().min(1).optional(),baseUrl:z$1.string().optional()});var ee="system",te="user",A="assistant",oe="tool",Fn=[ee,te,A,oe],Ge=z$1.enum(Fn),Kn=[A],Hn=z$1.enum(Kn),L="image",je="base64",Vn=["png","jpeg","webp","gif"],Jn=z$1.object({type:z$1.literal(je),base64:z$1.string(),mediaType:z$1.enum(Vn)}),Ae="url",Wn=z$1.object({type:z$1.literal(Ae),url:z$1.string()}),Yn=z$1.discriminatedUnion("type",[Jn,Wn]),Zn=["low","medium","high","auto"],Xn=z$1.enum(Zn),Qn=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(L),detail:Xn,value:Yn,metadata:e}),Gt="pdf",ea="base64",ta=z$1.object({type:z$1.literal(ea),base64:z$1.string()}),oa="url",na=z$1.object({type:z$1.literal(oa),url:z$1.string()}),aa=z$1.discriminatedUnion("type",[ta,na]),sa=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(Gt),value:aa,providerCacheKey:z$1.string(),metadata:e}),jt="reasoning",At="partial-reasoning",Lt="thinking",ia="redacted",Re=z$1.object({type:z$1.literal(Lt),thinking:z$1.string(),signature:z$1.string()}),Nt=z$1.object({type:z$1.literal(ia),data:z$1.string()}),ra=z$1.discriminatedUnion("type",[Re,Nt]),la=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(jt),value:ra,metadata:e}),ma=z$1.object({type:z$1.literal(Lt),thinking:Re.shape.thinking.optional(),signature:Re.shape.signature.optional()}),da=z$1.discriminatedUnion("type",[ma,Nt]),pa=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(At),value:da,metadata:e}),E="text",Ut=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(E),value:z$1.string(),metadata:e}),Le="partial-text",Bt=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(Le),value:z$1.string(),metadata:e}),G="tool-call",$t=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(G),index:z$1.number().int().nonnegative(),id:z$1.string().min(1),name:z$1.string().min(1),arguments:z$1.string(),metadata:e}),Ne="partial-tool-call",Dt=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(Ne),index:z$1.number().int().nonnegative(),id:z$1.string().optional(),name:z$1.string().optional(),arguments:z$1.string().optional(),metadata:e}),N="tool-response",ca=(e=z$1.undefined())=>z$1.object({modality:z$1.literal(N),index:z$1.number().int().nonnegative(),id:z$1.string().min(1),name:z$1.string().min(1),data:z$1.string(),apiResponse:z$1.object({statusCode:z$1.number().int().nonnegative()}).optional(),metadata:e}),ua=[E,L,Gt,G,N,jt],qt=z$1.enum(ua),ga=(e=z$1.undefined(),t=z$1.undefined(),n=z$1.undefined(),s=z$1.undefined(),i=z$1.undefined(),l=z$1.undefined())=>z$1.discriminatedUnion("modality",[Ut(e),Qn(t),sa(n),$t(s),ca(i),la(l)]),ha=[Le,Ne,At];z$1.enum(ha);var fa=(e=z$1.undefined(),t=z$1.undefined(),n=z$1.undefined())=>z$1.discriminatedUnion("modality",[Bt(e),Dt(t),pa(n)]);var Ue=(e=Ge,t=z$1.undefined(),n=z$1.undefined(),s=z$1.undefined(),i=z$1.undefined(),l=z$1.undefined(),r=z$1.undefined(),d=z$1.undefined())=>z$1.object({role:e,content:z$1.array(ga(t,n,s,i,r,l)),metadata:d}),Be=(e=Hn,t=z$1.undefined(),n=z$1.undefined(),s=z$1.undefined(),i=z$1.undefined())=>z$1.object({role:e,partialContent:fa(t,n,s),metadata:i}),_a=z$1.object({promptTokens:z$1.number().nonnegative(),completionTokens:z$1.number().nonnegative(),totalTokens:z$1.number().nonnegative()}),wt=z$1.object({token:z$1.string(),logProb:z$1.number(),bytes:z$1.array(z$1.number().int()).nullable()}),ba=wt.extend({topLogProbs:z$1.array(wt)}),zt=z$1.array(ba);z$1.object({messages:z$1.array(Ue()),usage:_a.optional(),logProbs:zt.optional()});var Ta=z$1.object({promptTokens:z$1.number().nonnegative().optional(),completionTokens:z$1.number().nonnegative().optional(),totalTokens:z$1.number().nonnegative().optional()});z$1.object({partialMessages:z$1.array(Be()),usage:Ta.optional(),logProbs:zt.optional()});var $e=(e=z$1.record(z$1.string(),z$1.any()).optional())=>e,ya=["object","array","number","string","boolean","enum"],It=z$1.enum(ya),Pa=z$1.object({anyOf:z$1.array(z$1.any()).optional(),type:z$1.union([It,z$1.array(z$1.union([It,z$1.literal("null")]))]).optional(),default:z$1.any().optional(),title:z$1.string().optional(),description:z$1.string().max(4096).optional(),properties:z$1.record(z$1.any()).optional(),required:z$1.array(z$1.string()).optional(),minItems:z$1.number().int().min(0).optional(),maxItems:z$1.number().int().optional(),items:z$1.record(z$1.any()).optional(),enum:z$1.array(z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()])).optional(),minimum:z$1.number().optional(),maximum:z$1.number().optional(),minLength:z$1.number().int().min(0).optional(),maxLength:z$1.number().int().optional(),$ref:z$1.string().optional()}),Oa=z$1.object({type:z$1.enum(["object"]),required:z$1.array(z$1.string()),$defs:z$1.record(z$1.any()).optional(),properties:z$1.record(Pa),additionalProperties:z$1.literal(!1)}),Ft=z$1.object({name:z$1.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:z$1.string().max(4096),strict:z$1.boolean().optional(),schema:Oa}).optional(),V="text",W="token",xa=[V,W],Kt=z$1.enum(xa),va=z$1.array(z$1.string().min(1)),Ma=z$1.array(z$1.array(z$1.number().int().nonnegative())),Ht=(e=z$1.undefined())=>z$1.discriminatedUnion("modality",[z$1.object({modality:z$1.literal(V),metadata:e,requests:va}),z$1.object({modality:z$1.literal(W),metadata:e,requests:Ma})]),De="float",ka=z$1.object({index:z$1.number().int().nonnegative(),embedding:z$1.array(z$1.number())}),qe="base64",Sa=z$1.object({index:z$1.number().int().nonnegative(),embedding:z$1.string().base64()}),Rt=z$1.object({totalTokens:z$1.number().int().nonnegative()});z$1.discriminatedUnion("encodingFormat",[z$1.object({encodingFormat:z$1.literal(De),embeddings:z$1.array(ka),usage:Rt.optional()}),z$1.object({encodingFormat:z$1.literal(qe),embeddings:z$1.array(Sa),usage:Rt.optional()})]);var Ca=e=>{let t=new WeakSet;return JSON.stringify(e,(n,s)=>{if(typeof s=="object"&&s!==null){if(t.has(s))return;t.add(s);}return s})},Ea=e=>e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:Ca(e),Ie="GatewayBaseError",z=class Vt extends Error{constructor({info:t,cause:n},s){super(`[${s!=null?s:Ie}]: ${t}
Message: ${Ea(n)}`),this.name=Ie,this.info=t,this.cause=n,this.name=s!=null?s:Ie,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof Vt}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},wa=z$1.object({inputPricePerMillion:z$1.number().nonnegative().describe("Price per 1M input tokens"),outputPricePerMillion:z$1.number().nonnegative().describe("Price per 1M output tokens")}).describe("Input/output price pair (per 1M tokens) for a specific category within a ChatModel pricing tier."),Ia=z$1.object({base:wa.describe("Base (uncached, non\u2011reasoning) rates")}).describe("Holds the `ChatModelTokenPairPrice` for different categories (e.g., base) within a single pricing tier."),Ra=z$1.object({minTokens:z$1.number().int().nonnegative().describe("Inclusive lower token bound for this tier."),maxTokens:z$1.number().int().nullable().optional().describe("Exclusive upper token bound; `null` means \u221E."),prices:Ia.describe("Price categories and rates for this specific token range.")}).refine(e=>e.maxTokens===null||typeof e.maxTokens=="number"&&e.maxTokens>e.minTokens,{message:"maxTokens must be > minTokens (or null for infinite).",path:["maxTokens"]}).describe("A single pricing tier defined by a token range and associated prices.");z$1.object({modelName:z$1.string().describe("Model name this schedule applies to."),currency:z$1.string().default("USD").describe("Currency code (e.g., USD)."),tokenRanges:z$1.array(Ra).min(1).describe("Pricing tiers (`ChatModelTokenRangePrice`) schedule, sorted by minTokens.")}).superRefine((e,t)=>{let{tokenRanges:n}=e;n[0].minTokens!==0&&t.addIssue({code:z$1.ZodIssueCode.custom,path:["tokenRanges",0,"minTokens"],message:"The first tier must have minTokens = 0."});for(let i=1;i<n.length;i++){let l=n[i-1],r=n[i];if(l.maxTokens===null){t.addIssue({code:z$1.ZodIssueCode.custom,path:["tokenRanges",i-1,"maxTokens"],message:"Cannot define any tokenRanges after an infinite tier (maxTokens = null)."});break}r.minTokens!==l.maxTokens&&t.addIssue({code:z$1.ZodIssueCode.custom,path:["tokenRanges",i,"minTokens"],message:`Tier ${i} minTokens (${r.minTokens}) must equal previous tier's maxTokens (${l.maxTokens}) for contiguity.`}),r.minTokens<l.minTokens&&t.addIssue({code:z$1.ZodIssueCode.custom,path:["tokenRanges",i,"minTokens"],message:`tokenRanges must be sorted by ascending minTokens. Tier ${i} (${r.minTokens}) starts before Tier ${i-1} (${l.minTokens}).`});}let s=n[n.length-1];n.every(i=>i.maxTokens!==null||i===s)&&s.maxTokens!==null&&t.addIssue({code:z$1.ZodIssueCode.custom,path:["tokenRanges",n.length-1,"maxTokens"],message:"The final tier must have maxTokens = null (representing infinity)."});}).describe("Complete pricing schedule for a single chat model, including all its token-based tiers.");var Ga="function";var ja=z$1.enum(["object","array","number","string","boolean","null"]),Aa=z$1.object({anyOf:z$1.array(z$1.any()).optional(),type:ja.optional(),default:z$1.any().optional(),title:z$1.string().optional(),description:z$1.string().max(4096).optional(),properties:z$1.record(z$1.any()).optional(),required:z$1.array(z$1.string()).optional(),minItems:z$1.number().int().min(0).optional(),maxItems:z$1.number().int().optional(),items:z$1.record(z$1.any()).optional(),enum:z$1.array(z$1.union([z$1.string(),z$1.number(),z$1.boolean(),z$1.null()])).optional(),minimum:z$1.number().optional(),maximum:z$1.number().optional(),minLength:z$1.number().int().min(0).optional(),maxLength:z$1.number().int().optional()});z$1.object({type:z$1.enum(["object"]),title:z$1.string().optional(),$defs:z$1.record(z$1.any()).optional(),properties:z$1.record(Aa).optional(),required:z$1.array(z$1.string()).optional()});var La=z$1.object({name:z$1.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:z$1.string().max(4096),parameters:z$1.any(),strict:z$1.boolean().optional()});var Na=z$1.enum(["function"]),Ua=z$1.object({maxAttempts:z$1.number().int().positive(),initialDelay:z$1.number().int().positive(),exponentialFactor:z$1.number().int().positive()}),Ba=z$1.object({type:z$1.literal("http"),method:z$1.enum(["get","post"]),url:z$1.string().url(),headers:z$1.record(z$1.string()).optional(),query:z$1.record(z$1.string()).optional(),body:z$1.record(z$1.any()).optional(),proxyUrl:z$1.string().url().optional(),proxyHeaders:z$1.record(z$1.string()).optional(),retry:Ua.optional()}),$a=z$1.discriminatedUnion("type",[Ba]),Da=z$1.object({type:Na,definition:z$1.object({schema:La}),request:$a.optional()}),qa=[Ga];z$1.enum(qa);var Jt=(e=z$1.undefined())=>z$1.discriminatedUnion("type",[Da.extend({metadata:e})]),ze=e=>Ut().parse({modality:E,value:e}),Wt=(e,t,n,s)=>$t().parse({modality:G,index:e,id:t,name:n,arguments:s});var Fe=(e,t)=>Be().parse({role:e,partialContent:Bt().parse({modality:Le,value:t})}),Yt=(e,t,n,s,i)=>Be().parse({role:e,partialContent:Dt().parse({modality:Ne,index:t,id:n,name:s,arguments:i})});var za=Object.defineProperty,Zt=Object.getOwnPropertySymbols,Fa=Object.prototype.hasOwnProperty,Ka=Object.prototype.propertyIsEnumerable,Xt=(e,t,n)=>t in e?za(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ne=(e,t)=>{for(var n in t||(t={}))Fa.call(t,n)&&Xt(e,n,t[n]);if(Zt)for(var n of Zt(t))Ka.call(t,n)&&Xt(e,n,t[n]);return e},Qt="ProviderError",Ke=class ro extends z{constructor({info:t,cause:n}){super({info:t,cause:n},Qt),this.name=Qt,this.info=t,this.cause=n;}static isProviderError(t){return t instanceof ro}},eo="ModelError",de=class lo extends z{constructor({info:t,cause:n}){super({info:t,cause:n},eo),this.name=eo,this.info=t,this.cause=n;}static isModelError(t){return t instanceof lo}},to="ModelResponseError",F=class mo extends z{constructor({info:t,cause:n}){super({info:t,cause:n},to),this.name=to,this.cause=n,this.info=t;}static isModelResponseError(t){return t instanceof mo}},oo="InvalidModelRequestError",ae=class po extends z{constructor({info:t,cause:n}){super({info:t,cause:n},oo),this.name=oo,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(t){return t instanceof po}},no="InvalidConfigError",K=class co extends z{constructor({info:t,cause:n}){super({info:t,cause:n},no),this.name=no,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(t){return t instanceof co}},ao="InvalidMessagesError",j=class uo extends z{constructor({info:t,cause:n}){super({info:t,cause:n},ao),this.name=ao,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(t){return t instanceof uo}},so="InvalidToolsError",He=class go extends z{constructor({info:t,cause:n}){super({info:t,cause:n},so),this.name=so,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof go}},io="InvalidEmbeddingRequestsError",ho=class fo extends z{constructor({info:t,cause:n}){super({info:t,cause:n},io),this.name=io,this.info=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(t){return t instanceof fo}},Ve="multi-string",_o=z$1.object({type:z$1.literal(Ve),param:z$1.string().min(1),title:z$1.string().min(1),description:z$1.string().min(1).max(500),max:z$1.number().int().positive()}),Ha=e=>z$1.array(z$1.string()).max(e).default([]).optional(),bo=e=>({def:_o.parse(ne({type:Ve},e)),schema:Ha(e.max)}),Je="object-schema",To=z$1.object({type:z$1.literal(Je),param:z$1.string().min(1),title:z$1.string().min(1),description:z$1.string().min(1).max(500),objectSchema:z$1.any()}),Va=e=>e.optional(),yo=e=>({def:To.parse(ne({type:Je},e)),schema:Va(e.objectSchema)}),We="range",Po=z$1.object({type:z$1.literal(We),param:z$1.string().min(1),title:z$1.string().min(1),description:z$1.string().min(1).max(500),min:z$1.number().int(),max:z$1.number().int(),step:z$1.number().positive(),default:z$1.number()}),Ja=(e,t,n,s)=>z$1.number().min(e).max(t).step(n).default(s).optional(),U=e=>({def:Po.parse(ne({type:We},e)),schema:Ja(e.min,e.max,e.step,e.default)}),Ye="select-boolean",Oo=z$1.object({type:z$1.literal(Ye),param:z$1.string().min(1),title:z$1.string().min(1),description:z$1.string().min(1).max(500),default:z$1.boolean().nullable()}),Wa=e=>z$1.boolean().nullable().default(e).optional(),xo=e=>({def:Oo.parse(ne({type:Ye},e)),schema:Wa(e.default)}),Ze="select-string",vo=z$1.object({type:z$1.literal(Ze),param:z$1.string().min(1),title:z$1.string().min(1),description:z$1.string().min(1).max(500),default:z$1.string(),choices:z$1.array(z$1.string())}),Ya=(e,t)=>z$1.enum(t).nullable().default(e).optional(),Y=e=>({def:vo.parse(ne({type:Ze},e)),schema:Ya(e.default,e.choices)}),Za=[We,Ve,Ze,Je,Ye];z$1.enum(Za);var Mo=z$1.discriminatedUnion("type",[Po,_o,vo,Oo,To]),g=(e=Ge,t=qt)=>z$1.object({name:z$1.string().min(1),description:z$1.string().min(1),roles:z$1.record(e,z$1.string().min(1).optional()),modalities:z$1.array(t).nonempty(),maxInputTokens:z$1.number().int().positive().min(1),maxOutputTokens:z$1.number().int().positive().min(1),maxReasoningTokens:z$1.number().int().positive().min(1).optional(),config:z$1.object({def:z$1.record(z$1.string().min(1),Mo),schema:z$1.instanceof(z$1.ZodObject)}).refine(n=>{var s,i;let l=Object.keys(n.def),r=Object.keys((i=(s=n.schema)==null?void 0:s.shape)!=null?i:{});return l.every(d=>r.includes(d))&&r.every(d=>l.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"}),price:z$1.custom()}),Z=(e=Kt)=>z$1.object({name:z$1.string().min(1),description:z$1.string().min(1),modalities:z$1.array(e).nonempty(),maxInputTokens:z$1.number().int().positive().min(1),maxOutputTokens:z$1.number().int().positive().min(1),config:z$1.object({def:z$1.record(z$1.string().min(1),Mo),schema:z$1.instanceof(z$1.ZodObject)}).refine(t=>{var n,s;let i=Object.keys(t.def),l=Object.keys((s=(n=t.schema)==null?void 0:n.shape)!=null?s:{});return i.every(r=>l.includes(r))&&l.every(r=>i.includes(r))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})});z$1.record(z$1.string());z$1.record(z$1.union([z$1.boolean(),z$1.string(),z$1.number(),z$1.object({}),z$1.array(z$1.any()),z$1.null(),z$1.undefined()]));z$1.string().url();var Xa={type:"range",title:"Temperature",description:"Adjusts the model's creativity level. With a setting of 0, the model strictly picks the most probable next word. For endeavors that benefit from a dash of inventiveness, consider dialing it up to 0.7 or higher, enabling the model to produce text that's unexpectedly fresh."},Qa={type:"range",title:"Max tokens",description:"Specify the total tokens for generation, where one token approximates four English characters. Setting this to 0 defaults to the model's maximum capacity."},es={type:"range",title:"Max reasoning tokens",description:"Specify the total tokens for reasoning, where one token approximates four English characters."},ts=e=>({type:"multi",title:"Stop sequence",description:`Enter up to ${e} sequences that will halt additional text output. The generated text will exclude these sequences.`}),os={type:"range",title:"Top A",description:"Considers only the top tokens that have 'sufficiently high' probabilities relative to the most likely token, functioning like a dynamic Top-P. A lower Top-A value narrows down the token choices based on the highest probability token, while a higher Top-A value refines the filtering without necessarily impacting the creativity of the output."},ns={type:"range",title:"Top P",description:"Selects a subset of likely tokens for generation, restricting choices to the top-P fraction of possibilities, such as the top 10% when P=0.1. This approach can limit the variety of the output. By default, it's set to 1, indicating no restriction. It's advised to adjust this parameter or temperature to modulate output diversity, but not to modify both simultaneously."},as={type:"range",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options."},ss={type:"range",title:"Min P",description:"Specifies the minimum probability a token must have to be considered, in relation to the probability of the most likely token. (This value varies based on the confidence level of the top token.) For example, if Min-P is set to 0.1, only tokens with at least 1/10th the probability of the highest-ranked token will be considered."},is={type:"range",title:"Frequency penalty",description:"Minimize redundancy. By assigning a penalty to frequently used tokens within the text, the likelihood of repeating identical phrases is reduced. The default setting for this penalty is zero."},rs={type:"range",title:"Presence penalty",description:"Enhance the introduction of novel subjects by reducing the preference for tokens that have already appeared in the text, thus boosting the chances of exploring fresh topics. The standard setting for this is zero."},ls={type:"range",title:"Seed",description:"When seed is fixed to a specific value, the model makes a best effort to provide the same response for repeated requests. Deterministic output isn't guaranteed. Also, changing the model or parameter settings, such as the temperature, can cause variations in the response even when you use the same seed value. By default, a random seed value is used."},ms={type:"range",title:"Repetition penalty",description:"Reduces the likelihood of repeating tokens from the input. Increasing this value makes the model less prone to repetition, but setting it too high may lead to less coherent output, often resulting in run-on sentences missing smaller words. The token penalty is scaled according to the original token's probability."},ds={type:"boolean",title:"Log probs",description:"Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned."},ps={type:"range",title:"Top log probs",description:"The number of most likely tokens to return at each token position, each with an associated log probability. 'logprobs' must be set to true if this parameter is used."},cs={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},us={type:"select",title:"Response format",description:"Choose the response format of your model. For JSON, you must include the string 'JSON' in some form within your system / user prompt."},gs={type:"select",title:"Response format",description:"Choose the response format of your model. 'json_object' colloquially known as JSON mode, instructs the model to respond with a valid JSON (must include the term 'json' in prompt). 'json_schema' colloquially known as structured outputs, allows you to specify a strict response schema that the model will adhere to."},hs={type:"object",title:"Response schema",description:"When response format is set to 'json_schema', the model will return a JSON object of the specified schema."},x={TEMPERATURE:Xa,MAX_TOKENS:Qa,STOP:ts,TOP_A:os,TOP_P:ns,TOP_K:as,MIN_P:ss,FREQUENCY_PENALTY:is,PRESENCE_PENALTY:rs,REPETITION_PENALTY:ms,SEED:ls,LOG_PROBS:ds,TOP_LOG_PROBS:ps,ECHO:cs,RESPONSE_FORMAT:us,RESPONSE_FORMAT_WITH_SCHEMA:gs,RESPONSE_SCHEMA:hs,MAX_REASONING_TOKENS:es};var Xe=e=>Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null));var ko=e=>e.split(";")[0].split("/")[1],X=e=>e==null?void 0:e.replace(/\/$/,"");var fs=Object.defineProperty,_s=Object.defineProperties,bs=Object.getOwnPropertyDescriptors,So=Object.getOwnPropertySymbols,Ts=Object.prototype.hasOwnProperty,ys=Object.prototype.propertyIsEnumerable,ce=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),Ps=e=>{throw TypeError(e)},Co=(e,t,n)=>t in e?fs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,w=(e,t)=>{for(var n in t||(t={}))Ts.call(t,n)&&Co(e,n,t[n]);if(So)for(var n of So(t))ys.call(t,n)&&Co(e,n,t[n]);return e},ue=(e,t)=>_s(e,bs(t)),R=(e,t,n)=>new Promise((s,i)=>{var l=c=>{try{d(n.next(c));}catch(u){i(u);}},r=c=>{try{d(n.throw(c));}catch(u){i(u);}},d=c=>c.done?s(c.value):Promise.resolve(c.value).then(l,r);d((n=n.apply(e,t)).next());}),wo=function(e,t){this[0]=e,this[1]=t;},Eo=(e,t,n)=>{var s=(r,d,c,u)=>{try{var M=n[r](d),b=(d=M.value)instanceof wo,k=M.done;Promise.resolve(b?d[0]:d).then(y=>b?s(r==="return"?r:"next",d[1]?{done:y.done,value:y.value}:y,c,u):c({value:y,done:k})).catch(y=>s("throw",y,c,u));}catch(y){u(y);}},i=r=>l[r]=d=>new Promise((c,u)=>s(r,d,c,u)),l={};return n=n.apply(e,t),l[ce("asyncIterator")]=()=>l,i("next"),i("throw"),i("return"),l},Os=e=>{var t=e[ce("asyncIterator")],n=!1,s,i={};return t==null?(t=e[ce("iterator")](),s=l=>i[l]=r=>t[l](r)):(t=t.call(e),s=l=>i[l]=r=>{if(n){if(n=!1,l==="throw")throw r;return r}return n=!0,{done:!1,value:new wo(new Promise(d=>{var c=t[l](r);c instanceof Object||Ps("Object expected"),d(c);}),1)}}),i[ce("iterator")]=()=>i,s("next"),"throw"in t?s("throw"):i.throw=l=>{throw l},"return"in t&&s("return"),i},Io=U({param:"temperature",title:x.TEMPERATURE.title,description:x.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),Ro=e=>U({param:"max_completion_tokens",title:x.MAX_TOKENS.title,description:x.MAX_TOKENS.description,min:0,max:e,step:1,default:0}),Go=e=>bo({param:"stop",title:x.STOP(e).title,description:x.STOP(e).description,max:e}),jo=U({param:"top_p",title:x.TOP_P.title,description:x.TOP_P.description,min:0,max:1,step:.01,default:1}),Ao=U({param:"frequency_penalty",title:x.FREQUENCY_PENALTY.title,description:x.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Lo=U({param:"presence_penalty",title:x.PRESENCE_PENALTY.title,description:x.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),No=U({param:"seed",title:x.SEED.title,description:x.SEED.description,min:0,max:1e6,step:1,default:0}),Uo=xo({param:"logprobs",title:x.LOG_PROBS.title,description:x.LOG_PROBS.description,default:!1}),Bo=U({param:"top_logprobs",title:x.TOP_LOG_PROBS.title,description:x.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),$o=Y({param:"tool_choice",title:"Tool choice",description:"Controls which (if any) tool is called by the model. 'none' means the model will not call a function. 'auto' means the model can pick between generating a message or calling a tool.",default:"auto",choices:["auto","required","none"]}),xt=(e,t)=>z$1.object({temperature:Io.schema,maxTokens:Ro(e).schema,stop:Go(t).schema,topP:jo.schema,frequencyPenalty:Ao.schema,presencePenalty:Lo.schema,seed:No.schema.transform(n=>n===0?void 0:n),logProbs:Uo.schema,topLogProbs:Bo.schema,toolChoice:$o.schema}),vt=(e,t)=>({temperature:Io.def,maxTokens:Ro(e).def,stop:Go(t).def,topP:jo.def,frequencyPenalty:Ao.def,presencePenalty:Lo.def,seed:No.def,logProbs:Uo.def,topLogProbs:Bo.def,toolChoice:$o.def}),Do=yo({param:"response_schema",title:x.RESPONSE_SCHEMA.title,description:x.RESPONSE_SCHEMA.description,objectSchema:Ft}),qo=Y({param:"response_format",title:x.RESPONSE_FORMAT_WITH_SCHEMA.title,description:x.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_object","json_schema"]}),zo=(e,t)=>ue(w({},vt(e,t)),{responseFormat:qo.def,responseSchema:Do.def}),Fo=(e,t)=>xt(e,t).extend({responseFormat:qo.schema,responseSchema:Do.schema}),Ko=U({param:"temperature",title:x.TEMPERATURE.title,description:x.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),Ho=Y({param:"reasoning_effort",title:"Reasoning Effort",description:"Constrains effort on reasoning for reasoning models. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.",default:"medium",choices:["low","medium","high"]}),xs=(e,t)=>ue(w({},zo(e,t)),{temperature:Ko.def,reasoningEffort:Ho.def}),vs=(e,t)=>Fo(e,t).extend({temperature:Ko.schema,reasoningEffort:Ho.schema}),Vo=Y({param:"response_format",title:x.RESPONSE_FORMAT.title,description:x.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),Ms=(e,t)=>ue(w({},vt(e,t)),{responseFormat:Vo.def}),ks=(e,t)=>xt(e,t).extend({responseFormat:Vo.schema}),Jo=Y({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),Wo=e=>U({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:e,step:1,default:e}),Yo=()=>z$1.object({encodingFormat:Jo.schema}),Zo=()=>({encodingFormat:Jo.def}),Ss=e=>Yo().extend({dimensions:Wo(e).schema}),Cs=e=>ue(w({},Zo()),{dimensions:Wo(e).def}),p={base:(e,t)=>({def:vt(e,t),schema:xt(e,t)}),responseFormat:(e,t)=>({def:Ms(e,t),schema:ks(e,t)}),responseSchema:(e,t)=>({def:zo(e,t),schema:Fo(e,t)}),oSeries:(e,t)=>({def:xs(e,t),schema:vs(e,t)})},H={base:()=>({def:Zo(),schema:Yo()}),dimensions:e=>({def:Cs(e),schema:Ss(e)})},v={"gpt-3.5-turbo-0125":{modelName:"gpt-3.5-turbo-0125",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gpt-3.5-turbo-1106":{modelName:"gpt-3.5-turbo-1106",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gpt-3.5-turbo":{modelName:"gpt-3.5-turbo",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gpt-4-0125-preview":{modelName:"gpt-4-0125-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4-0613":{modelName:"gpt-4-0613",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4-1106-preview":{modelName:"gpt-4-1106-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4-turbo-2024-04-09":{modelName:"gpt-4-turbo-2024-04-09",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:30}}}]},"gpt-4-turbo-preview":{modelName:"gpt-4-turbo-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:30}}}]},"gpt-4-turbo":{modelName:"gpt-4-turbo",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:30}}}]},"gpt-4":{modelName:"gpt-4",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:30,outputPricePerMillion:60}}}]},"gpt-4o-2024-05-13":{modelName:"gpt-4o-2024-05-13",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:5,outputPricePerMillion:20}}}]},"gpt-4o-2024-08-06":{modelName:"gpt-4o-2024-08-06",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gpt-4o-mini-2024-07-18":{modelName:"gpt-4o-mini-2024-07-18",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.6,outputPricePerMillion:2.4}}}]},"gpt-4o-mini":{modelName:"gpt-4o-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.6,outputPricePerMillion:2.4}}}]},"gpt-4o":{modelName:"gpt-4o",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:5,outputPricePerMillion:20}}}]},"o1-2024-12-17":{modelName:"o1-2024-12-17",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:60}}}]},o1:{modelName:"o1",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:60}}}]},"o3-mini-2025-01-31":{modelName:"o3-mini-2025-01-31",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o3-mini":{modelName:"o3-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o3-2025-04-16":{modelName:"o3-2025-04-16",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:40}}}]},o3:{modelName:"o3",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:10,outputPricePerMillion:40}}}]},"o4-mini-2025-04-16":{modelName:"o4-mini-2025-04-16",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o4-mini":{modelName:"o4-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"gpt-4.1":{modelName:"gpt-4.1",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:2,outputPricePerMillion:8}}}]},"gpt-4.1-mini":{modelName:"gpt-4.1-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.4,outputPricePerMillion:1.6}}}]},"gpt-4.1-nano":{modelName:"gpt-4.1-nano",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gpt-5":{modelName:"gpt-5",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gpt-5-mini":{modelName:"gpt-5-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.25,outputPricePerMillion:2}}}]},"gpt-5-nano":{modelName:"gpt-5-nano",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.05,outputPricePerMillion:.4}}}]},"gpt-5-chat-latest":{modelName:"gpt-5-chat-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]}},Es="openai",Mt=class{constructor(){this.version="v1",this.name=Es,this.chatModelFactories={[tt]:{model:ei,modelOptions:Qs,modelSchema:fe},[Qe]:{model:Js,modelOptions:Vs,modelSchema:ge},[et]:{model:Zs,modelOptions:Ys,modelSchema:he},[ot]:{model:ni,modelOptions:oi,modelSchema:Qo},[nt]:{model:ii,modelOptions:si,modelSchema:_e},[at]:{model:mi,modelOptions:li,modelSchema:be},[st]:{model:ci,modelOptions:pi,modelSchema:en},[it]:{model:hi,modelOptions:gi,modelSchema:tn},[rt]:{model:bi,modelOptions:_i,modelSchema:on},[lt]:{model:Pi,modelOptions:yi,modelSchema:nn},[mt]:{model:vi,modelOptions:xi,modelSchema:an},[dt]:{model:Si,modelOptions:ki,modelSchema:sn},[pt]:{model:Ri,modelOptions:Ii,modelSchema:rn},[ct]:{model:Ai,modelOptions:ji,modelSchema:Te},[ut]:{model:Ui,modelOptions:Ni,modelSchema:ln},[gt]:{model:Di,modelOptions:$i,modelSchema:mn},[ht]:{model:Fi,modelOptions:zi,modelSchema:ye},[_t]:{model:Yi,modelOptions:Wi,modelSchema:Oe},[Tt]:{model:or,modelOptions:tr,modelSchema:ve},[yt]:{model:sr,modelOptions:ar,modelSchema:Me},[bt]:{model:Qi,modelOptions:Xi,modelSchema:xe},[ft]:{model:Vi,modelOptions:Hi,modelSchema:Pe},[Ot]:{model:pr,modelOptions:dr,modelSchema:pn},[Pt]:{model:lr,modelOptions:rr,modelSchema:dn},[bn]:{model:xr,modelOptions:Or,modelSchema:Tn},[fn]:{model:yr,modelOptions:Tr,modelSchema:_n},[cn]:{model:gr,modelOptions:ur,modelSchema:un},[gn]:{model:_r,modelOptions:fr,modelSchema:hn},[yn]:{model:kr,modelOptions:Mr,modelSchema:Pn},[On]:{model:Er,modelOptions:Cr,modelSchema:xn}},this.embeddingModelFactories={[vn]:{model:Ar,modelOptions:jr,modelSchema:Se},[Mn]:{model:Ur,modelOptions:Nr,modelSchema:Ce},[kn]:{model:Dr,modelOptions:$r,modelSchema:Ee}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}chatModel(e){let t=e.modelName;if(!(t in this.chatModelFactories))throw new Ke({info:`OpenAI chat model: ${t} not found`,cause:new Error(`OpenAI chat model: ${t} not found, available chat models:
[${this.chatModelLiterals().join(", ")}]`)});let n=this.chatModelFactories[t].model,s=this.chatModelFactories[t].modelOptions.parse(e);return new n(s)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,t)=>(e[t]=this.embeddingModelFactories[t].modelSchema,e),{})}embeddingModel(e){let t=e.modelName;if(!(t in this.embeddingModelFactories))throw new Ke({info:`OpenAI embedding model: ${t} not found`,cause:new Error(`OpenAI embedding model: ${t} not found, available embedding models:
[${this.embeddingModelLiterals().join(", ")}]`)});let n=this.embeddingModelFactories[t].model,s=this.embeddingModelFactories[t].modelOptions.parse(e);return new n(s)}};Mt.baseUrl="https://api.openai.com/v1";var h=z$1.enum([ee,te,A,oe]),f={system:ee,user:te,assistant:A,tool:oe},S=[E,L,G,N],C=z$1.enum([E,L,G,N]);z$1.enum([E]);var B=[E,G,N],$=z$1.enum([E,G,N]),pe=z$1.object({token:z$1.string(),logprob:z$1.number(),bytes:z$1.array(z$1.number()).nullable()}),Xo=z$1.object({content:z$1.array(pe.extend({top_logprobs:z$1.array(pe)})).nullable().optional(),refusal:z$1.array(pe.extend({top_logprobs:z$1.array(pe)})).nullable().optional()}).nullable(),ws=z$1.array(z$1.object({id:z$1.string().min(1),type:z$1.enum(["function"]),function:z$1.object({name:z$1.string(),arguments:z$1.string()})})),Is=z$1.object({id:z$1.string(),object:z$1.literal("chat.completion"),created:z$1.number(),model:z$1.string(),system_fingerprint:z$1.string().nullable(),choices:z$1.array(z$1.object({index:z$1.number(),message:z$1.object({role:z$1.string(),content:z$1.string().nullable().optional(),tool_calls:ws.optional(),refusal:z$1.string().nullable().optional()}),logprobs:Xo.optional(),finish_reason:z$1.string()})),usage:z$1.object({prompt_tokens:z$1.number(),completion_tokens:z$1.number(),total_tokens:z$1.number()})}),Rs=z$1.array(z$1.object({index:z$1.number().int(),id:z$1.string().min(1).optional(),type:z$1.enum(["function"]).optional(),function:z$1.object({name:z$1.string().min(1).optional(),arguments:z$1.string().optional()}).optional()})),Gs=z$1.object({id:z$1.string(),object:z$1.string(),created:z$1.number(),model:z$1.string(),system_fingerprint:z$1.string().nullable().optional(),choices:z$1.array(z$1.object({index:z$1.number(),delta:z$1.object({content:z$1.string().nullable().optional(),tool_calls:Rs.optional(),refusal:z$1.string().nullable().optional()}).or(z$1.object({})),logprobs:Xo.optional(),finish_reason:z$1.string().nullable()})),usage:z$1.object({prompt_tokens:z$1.number(),completion_tokens:z$1.number(),total_tokens:z$1.number()}).nullable().optional()}),js=z$1.object({type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1),description:z$1.string().min(1).optional(),strict:z$1.boolean().optional(),parameters:z$1.any()})}),As=z$1.enum(["none","auto","required"]),Ls=z$1.object({type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1)})}),Ns=z$1.object({type:z$1.enum(["text","json_object"])}).or(z$1.object({type:z$1.literal("json_schema"),json_schema:z$1.object({name:z$1.string().min(1),description:z$1.string().min(1).optional(),strict:z$1.boolean().optional(),schema:z$1.any()})})),kt=z$1.object({text:z$1.string().min(1),type:z$1.literal("text")}),Us=z$1.object({type:z$1.literal("image_url"),image_url:z$1.object({url:z$1.string().url().min(1),detail:z$1.enum(["low","high","auto"]).optional()})}),Bs=z$1.object({id:z$1.string().min(1),type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1),arguments:z$1.string().min(1)})}),$s=z$1.object({role:z$1.literal("system"),content:z$1.string().min(1).or(z$1.array(kt).min(1))}),Ds=z$1.object({role:z$1.literal("user"),content:z$1.string().min(1).or(z$1.array(z$1.union([kt,Us])).min(1))}),qs=z$1.object({role:z$1.literal("assistant"),content:z$1.string().min(1).or(z$1.array(kt).min(1)).optional(),tool_calls:z$1.array(Bs).min(1).optional()}),zs=z$1.object({role:z$1.literal("tool"),tool_call_id:z$1.string().min(1),content:z$1.string().min(1)}),Fs=z$1.union([$s,Ds,qs,zs]),Ks=z$1.object({model:z$1.string().min(1).optional(),messages:z$1.array(Fs).min(1),frequency_penalty:z$1.number().min(-2).max(2).nullable().optional(),logprobs:z$1.boolean().nullable().optional(),top_logprobs:z$1.number().min(0).max(20).nullable().optional(),max_completion_tokens:z$1.number().min(0).nullable().optional(),presence_penalty:z$1.number().min(-2).max(2).nullable().optional(),response_format:Ns.optional(),seed:z$1.number().nullable().optional(),stop:z$1.string().or(z$1.array(z$1.string()).max(4)).nullable().optional(),temperature:z$1.number().min(0).max(2).nullable().optional(),top_p:z$1.number().min(0).max(1).nullable().optional(),tools:z$1.array(js).optional(),tool_choice:As.or(Ls).optional()}),T=z$1.object({modelName:z$1.string(),apiKey:z$1.string(),baseUrl:z$1.string().url().optional(),completeChatUrl:z$1.string().url().optional(),streamChatUrl:z$1.string().url().optional(),organization:z$1.string().optional()}),_=class{constructor(e,t){this.version="v1";let n=T.parse(t);this.modelSchema=e,this.modelName=n.modelName,this.apiKey=n.apiKey,this.baseUrl=X(n.baseUrl||Mt.baseUrl),this.streamChatUrl=X(n.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=X(n.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=n.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return w({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let t=r=>{let d=/(\d+)(h|m|s|ms)/g,c={h:36e5,m:6e4,s:1e3,ms:1},u,M=0;for(;(u=d.exec(r))!==null;){let b=parseInt(u[1]),k=u[2];M+=b*c[k];}return M},n=0,s=0,i=!0;e["x-ratelimit-reset-requests"]&&(n=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(s=t(e["x-ratelimit-reset-tokens"]));let l=Math.max(n,s);return {shouldRetry:i,delayMs:l}}getTokenCount(e){return e.reduce((t,n)=>t+n.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let t=Ks.safeParse(e);if(!t.success)throw new ae({info:"Invalid model request",cause:t.error});let n=t.data,s=n.model;if(n.tool_choice&&(!n.tools||n.tools.length===0))throw new ae({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let i={};n.response_format&&(i.responseFormat=n.response_format.type,n.response_format.type==="json_schema"&&(i.responseSchema={name:n.response_format.json_schema.name,description:n.response_format.json_schema.description||"",strict:n.response_format.json_schema.strict,schema:n.response_format.json_schema.schema})),n.tool_choice&&(typeof n.tool_choice=="string"?i.toolChoice=n.tool_choice:i.toolChoice=n.tool_choice.function.name),i.seed=n.seed,i.maxTokens=n.max_completion_tokens,i.temperature=n.temperature,i.topP=n.top_p,i.presencePenalty=n.presence_penalty,i.frequencyPenalty=n.frequency_penalty,i.stop=n.stop,i.logProbs=n.logprobs,i.topLogProbs=n.top_logprobs;let l=$e().parse(Xe(i)),r=[],d={};n.messages.forEach(u=>{let M=u.role;switch(M){case"system":{let b=u.content;if(typeof b=="string")r.push({role:M,content:[{modality:E,value:b}]});else {let k=b.map(y=>({modality:E,value:y.text}));r.push({role:M,content:k});}}break;case"user":{let b=u.content;if(typeof b=="string")r.push({role:M,content:[{modality:E,value:b}]});else {let k=b.map(y=>y.type==="text"?{modality:E,value:y.text}:y.image_url.url.startsWith("data:")?{modality:L,detail:y.image_url.detail||"auto",value:{type:je,base64:y.image_url.url,mediaType:ko(y.image_url.url)}}:{modality:L,detail:y.image_url.detail||"auto",value:{type:Ae,url:y.image_url.url}});r.push({role:M,content:k});}}break;case"assistant":{let b=[];if(!u.content&&!u.tool_calls)throw new ae({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(u.content){let k=u.content;typeof k=="string"?b.push({modality:E,value:k}):k.forEach(y=>{b.push({modality:E,value:y.text});});}u.tool_calls&&u.tool_calls.forEach((k,y)=>{let I={modality:G,id:k.id,index:y,name:k.function.name,arguments:k.function.arguments};b.push(I),d[I.id]=I;}),r.push({role:M,content:b});}break;case"tool":{let b=u;r.push({role:M,content:[{modality:N,id:b.tool_call_id,index:d[b.tool_call_id].index,name:d[b.tool_call_id].name,data:b.content}]});}break}});let c=[];return n.tools&&n.tools.forEach(u=>{c.push({type:"function",definition:{schema:{name:u.function.name,description:u.function.description||"",strict:u.function.strict,parameters:u.function.parameters}}});}),{modelName:s,config:l,messages:r,tools:c.length>0?c:void 0}}transformConfig(e,t,n){let s=e.toolChoice;delete e.toolChoice;let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new K({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let l=i.data;s!==void 0&&(l.toolChoice=s),Object.keys(l).forEach(d=>{if(!(d in this.modelSchema.config.def))throw new K({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${d}',
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let r=Object.keys(l).reduce((d,c)=>{let u=this.modelSchema.config.def[c],M=u.param,b=l[c];return M==="max_completion_tokens"&&u.type==="range"&&b===0?d[M]=u.max:d[M]=b,d},{});if(r.top_logprobs&&!r.logprobs)throw new K({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in r&&r.tool_choice!==void 0){let d=r.tool_choice;if(!n||n&&n.length===0)throw new K({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(n&&n.length>0){let c=this.modelSchema.config.def.toolChoice;if(!c.choices.includes(d))if(n.map(u=>u.definition.schema.name).includes(d))r.tool_choice={type:"function",function:{name:d}};else throw new K({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${d}' is not part of provided 'tools' names or
one of [${c.choices.join(", ")}]`)})}}if("response_format"in r&&r.response_format!==void 0){let d=r.response_format;if(d==="json_schema")if("response_schema"in r)r.response_format={type:"json_schema",json_schema:r.response_schema},delete r.response_schema;else throw new K({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else r.response_format={type:d};}return r}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=e.map(n=>{let s=Ue().safeParse(n);if(!s.success)throw new j({info:"Invalid messages",cause:s.error});return s.data});return t.forEach(n=>{n.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new j({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${s.modality}',
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(n=>{if(!Object.keys(this.modelSchema.roles).includes(n.role))throw new j({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${n.role}',
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),{messages:t.map(n=>{switch(n.role){case ee:{let s=[];return n.content.forEach(i=>{if(i.modality===E)s.push({type:"text",text:i.value});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${i.modality}'`)})}),{role:this.modelSchema.roles[n.role],content:s}}case A:{let s=[],i=[];return n.content.forEach(l=>{if(l.modality===E)s.push({type:"text",text:l.value});else if(l.modality===G)i.push({id:l.id,type:"function",function:{name:l.name,arguments:l.arguments}});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${l.modality}'`)})}),w({role:this.modelSchema.roles[n.role],content:s},i.length>0?{tool_calls:i}:{})}case te:{let s=[],i=[];n.content.forEach(r=>{if(r.modality===E)s.push({type:"text",text:r.value});else if(r.modality===L)i.push({type:"image_url",image_url:{url:r.value.type==="url"?r.value.url:r.value.base64,detail:r.detail}});else throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${r.modality}'`)})});let l=[...s,...i];return {role:this.modelSchema.roles[n.role],content:l}}case oe:{if(n.content.length!==1)throw new j({info:`Invalid message for role : '${n.role}'`,cause:new Error(`role : '${n.role}' must have exactly one content item`)});if(n.content[0].modality!==N)throw new j({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' must have content with modality : '${N}'`)});let s=n.content[0];return {role:this.modelSchema.roles[n.role],tool_call_id:s.id,content:s.data}}default:throw new j({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' is not supported,
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(e){if(!this.modelSchema.modalities.includes(G))throw new He({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${G}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(t=>{let n=Jt().safeParse(t);if(!n.success)throw new He({info:"Invalid tools",cause:n.error});return n.data}).map(t=>({type:"function",function:t.definition.schema}))}}getCompleteChatUrl(e,t,n){return R(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,n){return R(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getCompleteChatData(e,t,n){return R(this,null,function*(){let s=this.transformConfig(e,t,n),i=this.transformMessages(t);if(i.messages&&i.messages.length===0)throw new j({info:"Messages are required",cause:new Error("Messages are required")});let l=n?this.transformTools(n):{};return new Promise(r=>{r(w(w(w(w({},this.getDefaultParams()),s),i),l));})})}transformCompleteChatResponse(e){let t=Is.safeParse(e);if(t.success){if(t.data.choices.length===0)throw new F({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(t.data)}`)});let n=t.data,s=[{role:A,content:[]}],i=n.choices[0].message;i.content&&s[0].content.push(ze(i.content)),i.refusal&&s[0].content.push(ze(i.refusal)),i.tool_calls&&i.tool_calls.forEach((c,u)=>{s[0].content.push(Wt(u,c.id,c.function.name,c.function.arguments));});let l={promptTokens:n.usage.prompt_tokens,completionTokens:n.usage.completion_tokens,totalTokens:n.usage.total_tokens},r=[],d=n.choices[0].logprobs;return d&&(d.content&&r.push(...d.content.map(