@adaline/openai 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { ResponseSchema, SystemRoleLiteral, UserRoleLiteral, AssistantRoleLitera
4
4
 
5
5
  var Mn=Object.defineProperty,On=Object.defineProperties;var Cn=Object.getOwnPropertyDescriptors;var ct=Object.getOwnPropertySymbols;var bn=Object.prototype.hasOwnProperty,Pn=Object.prototype.propertyIsEnumerable;var ie=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Sn=s=>{throw TypeError(s)};var ut=(s,e,t)=>e in s?Mn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,O=(s,e)=>{for(var t in e||(e={}))bn.call(e,t)&&ut(s,t,e[t]);if(ct)for(var t of ct(e))Pn.call(e,t)&&ut(s,t,e[t]);return s},q=(s,e)=>On(s,Cn(e));var I=(s,e,t)=>new Promise((o,n)=>{var i=l=>{try{a(t.next(l));}catch(h){n(h);}},m=l=>{try{a(t.throw(l));}catch(h){n(h);}},a=l=>l.done?o(l.value):Promise.resolve(l.value).then(i,m);a((t=t.apply(s,e)).next());}),ht=function(s,e){this[0]=s,this[1]=e;},J=(s,e,t)=>{var o=(m,a,l,h)=>{try{var c=t[m](a),C=(a=c.value)instanceof ht,y=c.done;Promise.resolve(C?a[0]:a).then(M=>C?o(m==="return"?m:"next",a[1]?{done:M.done,value:M.value}:M,l,h):l({value:M,done:y})).catch(M=>o("throw",M,l,h));}catch(M){h(M);}},n=m=>i[m]=a=>new Promise((l,h)=>o(m,a,l,h)),i={};return t=t.apply(s,e),i[ie("asyncIterator")]=()=>i,n("next"),n("throw"),n("return"),i},re=s=>{var e=s[ie("asyncIterator")],t=!1,o,n={};return e==null?(e=s[ie("iterator")](),o=i=>n[i]=m=>e[i](m)):(e=e.call(s),o=i=>n[i]=m=>{if(t){if(t=!1,i==="throw")throw m;return m}return t=!0,{done:!1,value:new ht(new Promise(a=>{var l=e[i](m);l instanceof Object||Sn("Object expected"),a(l);}),1)}}),n[ie("iterator")]=()=>n,o("next"),"throw"in e?o("throw"):n.throw=i=>{throw i},"return"in e&&o("return"),n};var uo=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),ho=s=>RangeConfigItem({param:"max_completion_tokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:s,step:1,default:0}),fo=s=>MultiStringConfigItem({param:"stop",title:CHAT_CONFIG.STOP(s).title,description:CHAT_CONFIG.STOP(s).description,max:s}),go=RangeConfigItem({param:"top_p",title:CHAT_CONFIG.TOP_P.title,description:CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),_o=RangeConfigItem({param:"frequency_penalty",title:CHAT_CONFIG.FREQUENCY_PENALTY.title,description:CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),To=RangeConfigItem({param:"presence_penalty",title:CHAT_CONFIG.PRESENCE_PENALTY.title,description:CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),yo=RangeConfigItem({param:"seed",title:CHAT_CONFIG.SEED.title,description:CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),Mo=SelectBooleanConfigItem({param:"logprobs",title:CHAT_CONFIG.LOG_PROBS.title,description:CHAT_CONFIG.LOG_PROBS.description,default:!1}),Oo=RangeConfigItem({param:"top_logprobs",title:CHAT_CONFIG.TOP_LOG_PROBS.title,description:CHAT_CONFIG.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),Co=SelectStringConfigItem({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"]});var W=(s,e)=>z$1.object({temperature:uo.schema,maxTokens:ho(s).schema,stop:fo(e).schema,topP:go.schema,frequencyPenalty:_o.schema,presencePenalty:To.schema,seed:yo.schema.transform(t=>t===0?void 0:t),logProbs:Mo.schema,topLogProbs:Oo.schema,toolChoice:Co.schema}),Y=(s,e)=>({temperature:uo.def,maxTokens:ho(s).def,stop:fo(e).def,topP:go.def,frequencyPenalty:_o.def,presencePenalty:To.def,seed:yo.def,logProbs:Mo.def,topLogProbs:Oo.def,toolChoice:Co.def});var ft=ObjectSchemaConfigItem({param:"response_schema",title:CHAT_CONFIG.RESPONSE_SCHEMA.title,description:CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:ResponseSchema}),gt=SelectStringConfigItem({param:"response_format",title:CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.title,description:CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_object","json_schema"]}),pe=(s,e)=>q(O({},Y(s,e)),{responseFormat:gt.def,responseSchema:ft.def}),le=(s,e)=>W(s,e).extend({responseFormat:gt.schema,responseSchema:ft.schema});var Tt=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),yt=SelectStringConfigItem({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"]}),Mt=(s,e)=>q(O({},pe(s,e)),{temperature:Tt.def,reasoningEffort:yt.def}),Ot=(s,e)=>le(s,e).extend({temperature:Tt.schema,reasoningEffort:yt.schema});var bt=SelectStringConfigItem({param:"response_format",title:CHAT_CONFIG.RESPONSE_FORMAT.title,description:CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),Pt=(s,e)=>q(O({},Y(s,e)),{responseFormat:bt.def}),St=(s,e)=>W(s,e).extend({responseFormat:bt.schema});var bo=SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),Po=s=>RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:s,step:1,default:s});var me=()=>z$1.object({encodingFormat:bo.schema}),de=()=>({encodingFormat:bo.def});var It=s=>me().extend({dimensions:Po(s).schema}),xt=s=>q(O({},de()),{dimensions:Po(s).def});var r={base:(s,e)=>({def:Y(s,e),schema:W(s,e)}),responseFormat:(s,e)=>({def:Pt(s,e),schema:St(s,e)}),responseSchema:(s,e)=>({def:pe(s,e),schema:le(s,e)}),oSeries:(s,e)=>({def:Mt(s,e),schema:Ot(s,e)})},U={base:()=>({def:de(),schema:me()}),dimensions:s=>({def:xt(s),schema:It(s)})};var f={"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-preview":{modelName:"o1-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:60}}}]},"o1-mini-2024-09-12":{modelName:"o1-mini-2024-09-12",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},"o1-mini":{modelName:"o1-mini",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.1,outputPricePerMillion:4.4}}}]},o1:{modelName:"o1",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:15,outputPricePerMillion:60}}}]},"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}}}]}};var Un="openai",H=class{constructor(){this.version="v1";this.name=Un;this.chatModelFactories={[ge]:{model:_e,modelOptions:wt,modelSchema:xo},[ce]:{model:ue,modelOptions:At,modelSchema:So},[he]:{model:fe,modelOptions:Et,modelSchema:Io},[Te]:{model:ye,modelOptions:kt,modelSchema:Ro},[Me]:{model:Oe,modelOptions:Gt,modelSchema:Ao},[Ce]:{model:be,modelOptions:vt,modelSchema:Eo},[Pe]:{model:Se,modelOptions:qt,modelSchema:wo},[Ie]:{model:xe,modelOptions:Dt,modelSchema:ko},[Re]:{model:Ae,modelOptions:Lt,modelSchema:Go},[Ee]:{model:we,modelOptions:zt,modelSchema:vo},[ve]:{model:qe,modelOptions:Ut,modelSchema:Do},[ze]:{model:Be,modelOptions:jt,modelSchema:zo},[Ue]:{model:Ne,modelOptions:Ft,modelSchema:Bo},[De]:{model:Le,modelOptions:Nt,modelSchema:Lo},[ke]:{model:Ge,modelOptions:Bt,modelSchema:qo},[Ve]:{model:Ke,modelOptions:Vt,modelSchema:jo},[Je]:{model:We,modelOptions:Kt,modelSchema:Fo},[Ye]:{model:Qe,modelOptions:Jt,modelSchema:$o},[je]:{model:Fe,modelOptions:$t,modelSchema:Uo},[$e]:{model:He,modelOptions:Ht,modelSchema:No},[Ho]:{model:Xe,modelOptions:Wt,modelSchema:Vo},[Ko]:{model:Ze,modelOptions:Yt,modelSchema:Jo},[Wo]:{model:eo,modelOptions:Qt,modelSchema:Yo},[Qo]:{model:oo,modelOptions:Xt,modelSchema:Xo}};this.embeddingModelFactories={[Zo]:{model:to,modelOptions:Zt,modelSchema:et},[ot]:{model:no,modelOptions:en,modelSchema:tt},[nt]:{model:so,modelOptions:on,modelSchema:st}};}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 ProviderError({info:`OpenAI chat model: ${t} not found`,cause:new Error(`OpenAI chat model: ${t} not found, available chat models:
6
6
  [${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[t].model,n=this.chatModelFactories[t].modelOptions.parse(e);return new o(n)}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 ProviderError({info:`OpenAI embedding model: ${t} not found`,cause:new Error(`OpenAI embedding model: ${t} not found, available embedding models:
7
- [${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,n=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(n)}};H.baseUrl="https://api.openai.com/v1";var g=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),_={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral},D=z$1.enum([UserRoleLiteral,AssistantRoleLiteral]),L={user:UserRoleLiteral,assistant:AssistantRoleLiteral};var P=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],S=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),z=[TextModalityLiteral],B=z$1.enum([TextModalityLiteral]),A=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],E=z$1.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var lo=z$1.object({token:z$1.string(),logprob:z$1.number(),bytes:z$1.array(z$1.number()).nullable()}),an=z$1.object({content:z$1.array(lo.extend({top_logprobs:z$1.array(lo)})).nullable().optional(),refusal:z$1.array(lo.extend({top_logprobs:z$1.array(lo)})).nullable().optional()}).nullable(),Nn=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()})})),pn=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:Nn.optional(),refusal:z$1.string().nullable().optional()}),logprobs:an.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()})}),jn=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()})),ln=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:jn.optional(),refusal:z$1.string().nullable().optional()}).or(z$1.object({})),logprobs:an,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()});var Fn=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()})}),$n=z$1.enum(["none","auto","required"]),Hn=z$1.object({type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1)})}),Vn=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()})})),rt=z$1.object({text:z$1.string().min(1),type:z$1.literal("text")}),Kn=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()})}),Jn=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)})}),Wn=z$1.object({role:z$1.literal("system"),content:z$1.string().min(1).or(z$1.array(rt).min(1))}),Yn=z$1.object({role:z$1.literal("user"),content:z$1.string().min(1).or(z$1.array(z$1.union([rt,Kn])).min(1))}),Qn=z$1.object({role:z$1.literal("assistant"),content:z$1.string().min(1).or(z$1.array(rt).min(1)).optional(),tool_calls:z$1.array(Jn).min(1).optional()}),Xn=z$1.object({role:z$1.literal("tool"),tool_call_id:z$1.string().min(1),content:z$1.string().min(1)}),Zn=z$1.union([Wn,Yn,Qn,Xn]),mo=z$1.object({model:z$1.string().min(1).optional(),messages:z$1.array(Zn).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:Vn.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(Fn).optional(),tool_choice:$n.or(Hn).optional()});var mn=mo;var u=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()}),T=class{constructor(e,t){this.version="v1";let o=u.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl||H.baseUrl),this.streamChatUrl=urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return O({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let t=a=>{let l=/(\d+)(h|m|s|ms)/g,h={h:36e5,m:6e4,s:1e3,ms:1},c,C=0;for(;(c=l.exec(a))!==null;){let y=parseInt(c[1]),M=c[2];C+=y*h[M];}return C},o=0,n=0,i=!0;e["x-ratelimit-reset-requests"]&&(o=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(n=t(e["x-ratelimit-reset-tokens"]));let m=Math.max(o,n);return {shouldRetry:i,delayMs:m}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(n=>n.modality==="text"?n.value:"").join(" ").length,0)}transformModelRequest(e){let t=mo.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,n=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let i={};o.response_format&&(i.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(i.responseSchema={name:o.response_format.json_schema.name,description:o.response_format.json_schema.description||"",strict:o.response_format.json_schema.strict,schema:o.response_format.json_schema.schema})),o.tool_choice&&(typeof o.tool_choice=="string"?i.toolChoice=o.tool_choice:i.toolChoice=o.tool_choice.function.name),i.seed=o.seed,i.maxTokens=o.max_completion_tokens,i.temperature=o.temperature,i.topP=o.top_p,i.presencePenalty=o.presence_penalty,i.frequencyPenalty=o.frequency_penalty,i.stop=o.stop,i.logProbs=o.logprobs,i.topLogProbs=o.top_logprobs;let m=Config().parse(removeUndefinedEntries(i)),a=[],l={};o.messages.forEach(c=>{let C=c.role;switch(C){case"system":{let y=c.content;if(typeof y=="string")a.push({role:C,content:[{modality:TextModalityLiteral,value:y}]});else {let M=y.map(b=>({modality:TextModalityLiteral,value:b.text}));a.push({role:C,content:M});}}break;case"user":{let y=c.content;if(typeof y=="string")a.push({role:C,content:[{modality:TextModalityLiteral,value:y}]});else {let M=y.map(b=>b.type==="text"?{modality:TextModalityLiteral,value:b.text}:b.image_url.url.startsWith("data:")?{modality:ImageModalityLiteral,detail:b.image_url.detail||"auto",value:{type:Base64ImageContentTypeLiteral,base64:b.image_url.url,media_type:getMimeTypeFromBase64(b.image_url.url)}}:{modality:ImageModalityLiteral,detail:b.image_url.detail||"auto",value:{type:UrlImageContentTypeLiteral,url:b.image_url.url}});a.push({role:C,content:M});}}break;case"assistant":{let y=[];if(!c.content&&!c.tool_calls)throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(c.content){let M=c.content;typeof M=="string"?y.push({modality:TextModalityLiteral,value:M}):M.forEach(b=>{y.push({modality:TextModalityLiteral,value:b.text});});}c.tool_calls&&c.tool_calls.forEach((b,w)=>{let j={modality:ToolCallModalityLiteral,id:b.id,index:w,name:b.function.name,arguments:b.function.arguments};y.push(j),l[j.id]=j;}),a.push({role:C,content:y});}break;case"tool":{let y=c;a.push({role:C,content:[{modality:ToolResponseModalityLiteral,id:y.tool_call_id,index:l[y.tool_call_id].index,name:l[y.tool_call_id].name,data:y.content}]});}break}});let h=[];return o.tools&&o.tools.forEach(c=>{h.push({type:"function",definition:{schema:{name:c.function.name,description:c.function.description||"",strict:c.function.strict,parameters:c.function.parameters}}});}),{modelName:n,config:m,messages:a,tools:h.length>0?h:void 0}}transformConfig(e,t,o){let n=e.toolChoice;delete e.toolChoice;let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let m=i.data;n!==void 0&&(m.toolChoice=n),Object.keys(m).forEach(l=>{if(!(l in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${l}',
7
+ [${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,n=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(n)}};H.baseUrl="https://api.openai.com/v1";var g=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),_={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral},D=z$1.enum([UserRoleLiteral,AssistantRoleLiteral]),L={user:UserRoleLiteral,assistant:AssistantRoleLiteral};var P=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],S=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),z=[TextModalityLiteral],B=z$1.enum([TextModalityLiteral]),A=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],E=z$1.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var lo=z$1.object({token:z$1.string(),logprob:z$1.number(),bytes:z$1.array(z$1.number()).nullable()}),an=z$1.object({content:z$1.array(lo.extend({top_logprobs:z$1.array(lo)})).nullable().optional(),refusal:z$1.array(lo.extend({top_logprobs:z$1.array(lo)})).nullable().optional()}).nullable(),Nn=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()})})),pn=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:Nn.optional(),refusal:z$1.string().nullable().optional()}),logprobs:an.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()})}),jn=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()})),ln=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:jn.optional(),refusal:z$1.string().nullable().optional()}).or(z$1.object({})),logprobs:an,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()});var Fn=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()})}),$n=z$1.enum(["none","auto","required"]),Hn=z$1.object({type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1)})}),Vn=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()})})),rt=z$1.object({text:z$1.string().min(1),type:z$1.literal("text")}),Kn=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()})}),Jn=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)})}),Wn=z$1.object({role:z$1.literal("system"),content:z$1.string().min(1).or(z$1.array(rt).min(1))}),Yn=z$1.object({role:z$1.literal("user"),content:z$1.string().min(1).or(z$1.array(z$1.union([rt,Kn])).min(1))}),Qn=z$1.object({role:z$1.literal("assistant"),content:z$1.string().min(1).or(z$1.array(rt).min(1)).optional(),tool_calls:z$1.array(Jn).min(1).optional()}),Xn=z$1.object({role:z$1.literal("tool"),tool_call_id:z$1.string().min(1),content:z$1.string().min(1)}),Zn=z$1.union([Wn,Yn,Qn,Xn]),mo=z$1.object({model:z$1.string().min(1).optional(),messages:z$1.array(Zn).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:Vn.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(Fn).optional(),tool_choice:$n.or(Hn).optional()});var mn=mo;var u=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()}),T=class{constructor(e,t){this.version="v1";let o=u.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl||H.baseUrl),this.streamChatUrl=urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return O({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(e){let t=a=>{let l=/(\d+)(h|m|s|ms)/g,h={h:36e5,m:6e4,s:1e3,ms:1},c,C=0;for(;(c=l.exec(a))!==null;){let y=parseInt(c[1]),M=c[2];C+=y*h[M];}return C},o=0,n=0,i=!0;e["x-ratelimit-reset-requests"]&&(o=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(n=t(e["x-ratelimit-reset-tokens"]));let m=Math.max(o,n);return {shouldRetry:i,delayMs:m}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(n=>n.modality==="text"?n.value:"").join(" ").length,0)}transformModelRequest(e){let t=mo.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,n=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let i={};o.response_format&&(i.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(i.responseSchema={name:o.response_format.json_schema.name,description:o.response_format.json_schema.description||"",strict:o.response_format.json_schema.strict,schema:o.response_format.json_schema.schema})),o.tool_choice&&(typeof o.tool_choice=="string"?i.toolChoice=o.tool_choice:i.toolChoice=o.tool_choice.function.name),i.seed=o.seed,i.maxTokens=o.max_completion_tokens,i.temperature=o.temperature,i.topP=o.top_p,i.presencePenalty=o.presence_penalty,i.frequencyPenalty=o.frequency_penalty,i.stop=o.stop,i.logProbs=o.logprobs,i.topLogProbs=o.top_logprobs;let m=Config().parse(removeUndefinedEntries(i)),a=[],l={};o.messages.forEach(c=>{let C=c.role;switch(C){case"system":{let y=c.content;if(typeof y=="string")a.push({role:C,content:[{modality:TextModalityLiteral,value:y}]});else {let M=y.map(b=>({modality:TextModalityLiteral,value:b.text}));a.push({role:C,content:M});}}break;case"user":{let y=c.content;if(typeof y=="string")a.push({role:C,content:[{modality:TextModalityLiteral,value:y}]});else {let M=y.map(b=>b.type==="text"?{modality:TextModalityLiteral,value:b.text}:b.image_url.url.startsWith("data:")?{modality:ImageModalityLiteral,detail:b.image_url.detail||"auto",value:{type:Base64ImageContentTypeLiteral,base64:b.image_url.url,mediaType:getMimeTypeFromBase64(b.image_url.url)}}:{modality:ImageModalityLiteral,detail:b.image_url.detail||"auto",value:{type:UrlImageContentTypeLiteral,url:b.image_url.url}});a.push({role:C,content:M});}}break;case"assistant":{let y=[];if(!c.content&&!c.tool_calls)throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(c.content){let M=c.content;typeof M=="string"?y.push({modality:TextModalityLiteral,value:M}):M.forEach(b=>{y.push({modality:TextModalityLiteral,value:b.text});});}c.tool_calls&&c.tool_calls.forEach((b,w)=>{let j={modality:ToolCallModalityLiteral,id:b.id,index:w,name:b.function.name,arguments:b.function.arguments};y.push(j),l[j.id]=j;}),a.push({role:C,content:y});}break;case"tool":{let y=c;a.push({role:C,content:[{modality:ToolResponseModalityLiteral,id:y.tool_call_id,index:l[y.tool_call_id].index,name:l[y.tool_call_id].name,data:y.content}]});}break}});let h=[];return o.tools&&o.tools.forEach(c=>{h.push({type:"function",definition:{schema:{name:c.function.name,description:c.function.description||"",strict:c.function.strict,parameters:c.function.parameters}}});}),{modelName:n,config:m,messages:a,tools:h.length>0?h:void 0}}transformConfig(e,t,o){let n=e.toolChoice;delete e.toolChoice;let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let m=i.data;n!==void 0&&(m.toolChoice=n),Object.keys(m).forEach(l=>{if(!(l in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${l}',
8
8
  available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let a=Object.keys(m).reduce((l,h)=>{let c=this.modelSchema.config.def[h],C=c.param,y=m[h];return C==="max_completion_tokens"&&c.type==="range"&&y===0?l[C]=c.max:l[C]=y,l},{});if(a.top_logprobs&&!a.logprobs)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in a&&a.tool_choice!==void 0){let l=a.tool_choice;if(!o||o&&o.length===0)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let h=this.modelSchema.config.def.toolChoice;if(!h.choices.includes(l))if(o.map(c=>c.definition.schema.name).includes(l))a.tool_choice={type:"function",function:{name:l}};else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${l}' is not part of provided 'tools' names or
9
9
  one of [${h.choices.join(", ")}]`)})}}if("response_format"in a&&a.response_format!==void 0){let l=a.response_format;if(l==="json_schema")if("response_schema"in a)a.response_format={type:"json_schema",json_schema:a.response_schema},delete a.response_schema;else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else a.response_format={type:l};}return a}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=e.map(n=>{let i=Message().safeParse(n);if(!i.success)throw new InvalidMessagesError({info:"Invalid messages",cause:i.error});return i.data});return t.forEach(n=>{n.content.forEach(i=>{if(!this.modelSchema.modalities.includes(i.modality))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${i.modality}',
10
10
  available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(n=>{if(!Object.keys(this.modelSchema.roles).includes(n.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${n.role}',