@adaline/openai
Version:
Adaline OpenAI
16 lines (14 loc) • 57 kB
JavaScript
'use strict';
var zod = require('zod');
var provider = require('@adaline/provider');
var types = require('@adaline/types');
var yn=Object.defineProperty,On=Object.defineProperties;var Cn=Object.getOwnPropertyDescriptors;var lt=Object.getOwnPropertySymbols;var bn=Object.prototype.hasOwnProperty,Pn=Object.prototype.propertyIsEnumerable;var X=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),Sn=n=>{throw TypeError(n)};var pt=(n,e,t)=>e in n?yn(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,P=(n,e)=>{for(var t in e||(e={}))bn.call(e,t)&&pt(n,t,e[t]);if(lt)for(var t of lt(e))Pn.call(e,t)&&pt(n,t,e[t]);return n},L=(n,e)=>On(n,Cn(e));var A=(n,e,t)=>new Promise((o,s)=>{var i=p=>{try{r(t.next(p));}catch(g){s(g);}},m=p=>{try{r(t.throw(p));}catch(g){s(g);}},r=p=>p.done?o(p.value):Promise.resolve(p.value).then(i,m);r((t=t.apply(n,e)).next());}),mt=function(n,e){this[0]=n,this[1]=e;},no=(n,e,t)=>{var o=(m,r,p,g)=>{try{var _=t[m](r),b=(r=_.value)instanceof mt,O=_.done;Promise.resolve(b?r[0]:r).then(C=>b?o(m==="return"?m:"next",r[1]?{done:C.done,value:C.value}:C,p,g):p({value:C,done:O})).catch(C=>o("throw",C,p,g));}catch(C){g(C);}},s=m=>i[m]=r=>new Promise((p,g)=>o(m,r,p,g)),i={};return t=t.apply(n,e),i[X("asyncIterator")]=()=>i,s("next"),s("throw"),s("return"),i},dt=n=>{var e=n[X("asyncIterator")],t=!1,o,s={};return e==null?(e=n[X("iterator")](),o=i=>s[i]=m=>e[i](m)):(e=e.call(n),o=i=>s[i]=m=>{if(t){if(t=!1,i==="throw")throw m;return m}return t=!0,{done:!1,value:new mt(new Promise(r=>{var p=e[i](m);p instanceof Object||Sn("Object expected"),r(p);}),1)}}),s[X("iterator")]=()=>s,o("next"),"throw"in e?o("throw"):s.throw=i=>{throw i},"return"in e&&o("return"),s};var so=provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),io=n=>provider.RangeConfigItem({param:"max_completion_tokens",title:provider.CHAT_CONFIG.MAX_TOKENS.title,description:provider.CHAT_CONFIG.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),ao=n=>provider.MultiStringConfigItem({param:"stop",title:provider.CHAT_CONFIG.STOP(n).title,description:provider.CHAT_CONFIG.STOP(n).description,max:n}),ro=provider.RangeConfigItem({param:"top_p",title:provider.CHAT_CONFIG.TOP_P.title,description:provider.CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),lo=provider.RangeConfigItem({param:"frequency_penalty",title:provider.CHAT_CONFIG.FREQUENCY_PENALTY.title,description:provider.CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),po=provider.RangeConfigItem({param:"presence_penalty",title:provider.CHAT_CONFIG.PRESENCE_PENALTY.title,description:provider.CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),mo=provider.RangeConfigItem({param:"seed",title:provider.CHAT_CONFIG.SEED.title,description:provider.CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),co=provider.SelectBooleanConfigItem({param:"logprobs",title:provider.CHAT_CONFIG.LOG_PROBS.title,description:provider.CHAT_CONFIG.LOG_PROBS.description,default:!1}),uo=provider.RangeConfigItem({param:"top_logprobs",title:provider.CHAT_CONFIG.TOP_LOG_PROBS.title,description:provider.CHAT_CONFIG.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),ho=provider.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 F=(n,e)=>zod.z.object({temperature:so.schema,maxTokens:io(n).schema,stop:ao(e).schema,topP:ro.schema,frequencyPenalty:lo.schema,presencePenalty:po.schema,seed:mo.schema.transform(t=>t===0?void 0:t),logProbs:co.schema,topLogProbs:uo.schema,toolChoice:ho.schema}),$=(n,e)=>({temperature:so.def,maxTokens:io(n).def,stop:ao(e).def,topP:ro.def,frequencyPenalty:lo.def,presencePenalty:po.def,seed:mo.def,logProbs:co.def,topLogProbs:uo.def,toolChoice:ho.def});var ct=provider.ObjectSchemaConfigItem({param:"response_schema",title:provider.CHAT_CONFIG.RESPONSE_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:types.ResponseSchema}),ut=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_object","json_schema"]}),ee=(n,e)=>L(P({},$(n,e)),{responseFormat:ut.def,responseSchema:ct.def}),oe=(n,e)=>F(n,e).extend({responseFormat:ut.schema,responseSchema:ct.schema});var ft=provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),_t=provider.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"]}),gt=(n,e)=>L(P({},ee(n,e)),{temperature:ft.def,reasoningEffort:_t.def}),Tt=(n,e)=>oe(n,e).extend({temperature:ft.schema,reasoningEffort:_t.schema});var yt=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),Ot=(n,e)=>L(P({},$(n,e)),{responseFormat:yt.def}),Ct=(n,e)=>F(n,e).extend({responseFormat:yt.schema});var fo=provider.SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),_o=n=>provider.RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:n,step:1,default:n});var te=()=>zod.z.object({encodingFormat:fo.schema}),ne=()=>({encodingFormat:fo.def});var bt=n=>te().extend({dimensions:_o(n).schema}),Pt=n=>L(P({},ne()),{dimensions:_o(n).def});var a={base:(n,e)=>({def:$(n,e),schema:F(n,e)}),responseFormat:(n,e)=>({def:Ot(n,e),schema:Ct(n,e)}),responseSchema:(n,e)=>({def:ee(n,e),schema:oe(n,e)}),oSeries:(n,e)=>({def:gt(n,e),schema:Tt(n,e)})},v={base:()=>({def:ne(),schema:te()}),dimensions:n=>({def:Pt(n),schema:bt(n)})};var T={"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}}}]}};var Bn="openai",B=class{constructor(){this.version="v1";this.name=Bn;this.chatModelFactories={[le]:{model:pe,modelOptions:Rt,modelSchema:Mo},[se]:{model:ie,modelOptions:It,modelSchema:go},[ae]:{model:re,modelOptions:xt,modelSchema:To},[me]:{model:de,modelOptions:At,modelSchema:yo},[ce]:{model:ue,modelOptions:Et,modelSchema:Oo},[he]:{model:fe,modelOptions:Gt,modelSchema:Co},[_e]:{model:ge,modelOptions:kt,modelSchema:bo},[Te]:{model:Me,modelOptions:wt,modelSchema:Po},[ye]:{model:Oe,modelOptions:vt,modelSchema:So},[Ce]:{model:be,modelOptions:qt,modelSchema:Io},[Pe]:{model:Se,modelOptions:Dt,modelSchema:xo},[Ie]:{model:xe,modelOptions:Lt,modelSchema:Ro},[Re]:{model:Ae,modelOptions:Nt,modelSchema:Ao},[ke]:{model:we,modelOptions:Bt,modelSchema:Go},[De]:{model:Le,modelOptions:jt,modelSchema:wo},[Ne]:{model:ze,modelOptions:Ft,modelSchema:vo},[ve]:{model:qe,modelOptions:Ut,modelSchema:ko},[Ee]:{model:Ge,modelOptions:zt,modelSchema:Eo},[je]:{model:Fe,modelOptions:Ht,modelSchema:Do},[Be]:{model:Ue,modelOptions:$t,modelSchema:qo},[Fo]:{model:Ke,modelOptions:Wt,modelSchema:$o},[Uo]:{model:Ve,modelOptions:Jt,modelSchema:jo},[Lo]:{model:$e,modelOptions:Vt,modelSchema:No},[zo]:{model:He,modelOptions:Kt,modelSchema:Bo},[Ho]:{model:Je,modelOptions:Yt,modelSchema:Vo},[Ko]:{model:We,modelOptions:Qt,modelSchema:Jo}};this.embeddingModelFactories={[Wo]:{model:Ye,modelOptions:Xt,modelSchema:Yo},[Qo]:{model:Qe,modelOptions:Zt,modelSchema:Xo},[Zo]:{model:Xe,modelOptions:en,modelSchema:et}};}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 provider.ProviderError({info:`OpenAI chat model: ${t} not found`,cause:new Error(`OpenAI chat model: ${t} not found, available chat models:
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[t].model,s=this.chatModelFactories[t].modelOptions.parse(e);return new o(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 provider.ProviderError({info:`OpenAI embedding model: ${t} not found`,cause:new Error(`OpenAI embedding model: ${t} not found, available embedding models:
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,s=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(s)}};B.baseUrl="https://api.openai.com/v1";var h=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),f={system:types.SystemRoleLiteral,user:types.UserRoleLiteral,assistant:types.AssistantRoleLiteral,tool:types.ToolRoleLiteral};var M=[types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],y=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]),Ma=[types.TextModalityLiteral],ya=zod.z.enum([types.TextModalityLiteral]),I=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],x=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var oo=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),rn=zod.z.object({content:zod.z.array(oo.extend({top_logprobs:zod.z.array(oo)})).nullable().optional(),refusal:zod.z.array(oo.extend({top_logprobs:zod.z.array(oo)})).nullable().optional()}).nullable(),jn=zod.z.array(zod.z.object({id:zod.z.string().min(1),type:zod.z.enum(["function"]),function:zod.z.object({name:zod.z.string(),arguments:zod.z.string()})})),ln=zod.z.object({id:zod.z.string(),object:zod.z.literal("chat.completion"),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.string().nullable(),choices:zod.z.array(zod.z.object({index:zod.z.number(),message:zod.z.object({role:zod.z.string(),content:zod.z.string().nullable().optional(),tool_calls:jn.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:rn.optional(),finish_reason:zod.z.string()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()})}),Fn=zod.z.array(zod.z.object({index:zod.z.number().int(),id:zod.z.string().min(1).optional(),type:zod.z.enum(["function"]).optional(),function:zod.z.object({name:zod.z.string().min(1).optional(),arguments:zod.z.string().optional()}).optional()})),pn=zod.z.object({id:zod.z.string(),object:zod.z.string(),created:zod.z.number(),model:zod.z.string(),system_fingerprint:zod.z.string().nullable().optional(),choices:zod.z.array(zod.z.object({index:zod.z.number(),delta:zod.z.object({content:zod.z.string().nullable().optional(),tool_calls:Fn.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:rn.optional(),finish_reason:zod.z.string().nullable()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()}).nullable().optional()});var $n=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),parameters:zod.z.any()})}),Hn=zod.z.enum(["none","auto","required"]),Vn=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),Kn=zod.z.object({type:zod.z.enum(["text","json_object"])}).or(zod.z.object({type:zod.z.literal("json_schema"),json_schema:zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),strict:zod.z.boolean().optional(),schema:zod.z.any()})})),tt=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),Jn=zod.z.object({type:zod.z.literal("image_url"),image_url:zod.z.object({url:zod.z.string().url().min(1),detail:zod.z.enum(["low","high","auto"]).optional()})}),Wn=zod.z.object({id:zod.z.string().min(1),type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1),arguments:zod.z.string().min(1)})}),Yn=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(tt).min(1))}),Qn=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([tt,Jn])).min(1))}),Xn=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(tt).min(1)).optional(),tool_calls:zod.z.array(Wn).min(1).optional()}),Zn=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),es=zod.z.union([Yn,Qn,Xn,Zn]),mn=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(es).min(1),frequency_penalty:zod.z.number().min(-2).max(2).nullable().optional(),logprobs:zod.z.boolean().nullable().optional(),top_logprobs:zod.z.number().min(0).max(20).nullable().optional(),max_completion_tokens:zod.z.number().min(0).nullable().optional(),presence_penalty:zod.z.number().min(-2).max(2).nullable().optional(),response_format:Kn.optional(),seed:zod.z.number().nullable().optional(),stop:zod.z.string().or(zod.z.array(zod.z.string()).max(4)).nullable().optional(),temperature:zod.z.number().min(0).max(2).nullable().optional(),top_p:zod.z.number().min(0).max(1).nullable().optional(),tools:zod.z.array($n).optional(),tool_choice:Hn.or(Vn).optional()});var u=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional(),organization:zod.z.string().optional()}),c=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=provider.urlWithoutTrailingSlash(o.baseUrl||B.baseUrl),this.streamChatUrl=provider.urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/chat/completions`),this.completeChatUrl=provider.urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/chat/completions`),this.organization=o.organization;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return P({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 p=/(\d+)(h|m|s|ms)/g,g={h:36e5,m:6e4,s:1e3,ms:1},_,b=0;for(;(_=p.exec(r))!==null;){let O=parseInt(_[1]),C=_[2];b+=O*g[C];}return b},o=0,s=0,i=!0;e["x-ratelimit-reset-requests"]&&(o=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(s=t(e["x-ratelimit-reset-tokens"]));let m=Math.max(o,s);return {shouldRetry:i,delayMs:m}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let t=mn.safeParse(e);if(!t.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model;if(o.tool_choice&&(!o.tools||o.tools.length===0))throw new provider.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=types.Config().parse(provider.removeUndefinedEntries(i)),r=[],p={};o.messages.forEach(_=>{let b=_.role;switch(b){case"system":{let O=_.content;if(typeof O=="string")r.push({role:b,content:[{modality:types.TextModalityLiteral,value:O}]});else {let C=O.map(S=>({modality:types.TextModalityLiteral,value:S.text}));r.push({role:b,content:C});}}break;case"user":{let O=_.content;if(typeof O=="string")r.push({role:b,content:[{modality:types.TextModalityLiteral,value:O}]});else {let C=O.map(S=>S.type==="text"?{modality:types.TextModalityLiteral,value:S.text}:S.image_url.url.startsWith("data:")?{modality:types.ImageModalityLiteral,detail:S.image_url.detail||"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:S.image_url.url,mediaType:provider.getMimeTypeFromBase64(S.image_url.url)}}:{modality:types.ImageModalityLiteral,detail:S.image_url.detail||"auto",value:{type:types.UrlImageContentTypeLiteral,url:S.image_url.url}});r.push({role:b,content:C});}}break;case"assistant":{let O=[];if(!_.content&&!_.tool_calls)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(_.content){let C=_.content;typeof C=="string"?O.push({modality:types.TextModalityLiteral,value:C}):C.forEach(S=>{O.push({modality:types.TextModalityLiteral,value:S.text});});}_.tool_calls&&_.tool_calls.forEach((S,E)=>{let D={modality:types.ToolCallModalityLiteral,id:S.id,index:E,name:S.function.name,arguments:S.function.arguments};O.push(D),p[D.id]=D;}),r.push({role:b,content:O});}break;case"tool":{let O=_;r.push({role:b,content:[{modality:types.ToolResponseModalityLiteral,id:O.tool_call_id,index:p[O.tool_call_id].index,name:p[O.tool_call_id].name,data:O.content}]});}break}});let g=[];return o.tools&&o.tools.forEach(_=>{g.push({type:"function",definition:{schema:{name:_.function.name,description:_.function.description||"",strict:_.function.strict,parameters:_.function.parameters}}});}),{modelName:s,config:m,messages:r,tools:g.length>0?g:void 0}}transformConfig(e,t,o){let s=e.toolChoice;delete e.toolChoice;let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let m=i.data;s!==void 0&&(m.toolChoice=s),Object.keys(m).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${p}',
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let r=Object.keys(m).reduce((p,g)=>{let _=this.modelSchema.config.def[g],b=_.param,O=m[g];return b==="max_completion_tokens"&&_.type==="range"&&O===0?p[b]=_.max:p[b]=O,p},{});if(r.top_logprobs&&!r.logprobs)throw new provider.InvalidConfigError({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 p=r.tool_choice;if(!o||o&&o.length===0)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let g=this.modelSchema.config.def.toolChoice;if(!g.choices.includes(p))if(o.map(_=>_.definition.schema.name).includes(p))r.tool_choice={type:"function",function:{name:p}};else throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${p}' is not part of provided 'tools' names or
one of [${g.choices.join(", ")}]`)})}}if("response_format"in r&&r.response_format!==void 0){let p=r.response_format;if(p==="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 provider.InvalidConfigError({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:p};}return r}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=e.map(s=>{let i=types.Message().safeParse(s);if(!i.success)throw new provider.InvalidMessagesError({info:"Invalid messages",cause:i.error});return i.data});return t.forEach(s=>{s.content.forEach(i=>{if(!this.modelSchema.modalities.includes(i.modality))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${i.modality}',
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(s=>{if(!Object.keys(this.modelSchema.roles).includes(s.role))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${s.role}',
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),{messages:t.map(s=>{switch(s.role){case types.SystemRoleLiteral:{let i=[];return s.content.forEach(m=>{if(m.modality===types.TextModalityLiteral)i.push({type:"text",text:m.value});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${m.modality}'`)})}),{role:this.modelSchema.roles[s.role],content:i}}case types.AssistantRoleLiteral:{let i=[],m=[];return s.content.forEach(r=>{if(r.modality===types.TextModalityLiteral)i.push({type:"text",text:r.value});else if(r.modality===types.ToolCallModalityLiteral)m.push({id:r.id,type:"function",function:{name:r.name,arguments:r.arguments}});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${r.modality}'`)})}),P({role:this.modelSchema.roles[s.role],content:i},m.length>0?{tool_calls:m}:{})}case types.UserRoleLiteral:{let i=[],m=[];s.content.forEach(p=>{if(p.modality===types.TextModalityLiteral)i.push({type:"text",text:p.value});else if(p.modality===types.ImageModalityLiteral)m.push({type:"image_url",image_url:{url:p.value.type==="url"?p.value.url:p.value.base64,detail:p.detail}});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${p.modality}'`)})});let r=[...i,...m];return {role:this.modelSchema.roles[s.role],content:r}}case types.ToolRoleLiteral:{if(s.content.length!==1)throw new provider.InvalidMessagesError({info:`Invalid message for role : '${s.role}'`,cause:new Error(`role : '${s.role}' must have exactly one content item`)});if(s.content[0].modality!==types.ToolResponseModalityLiteral)throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${s.role}' must have content with modality : '${types.ToolResponseModalityLiteral}'`)});let i=s.content[0];return {role:this.modelSchema.roles[s.role],tool_call_id:i.id,content:i.data}}default:throw new provider.InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${s.role}' is not supported,
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(e){if(!this.modelSchema.modalities.includes(types.ToolCallModalityLiteral))throw new provider.InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${types.ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(s=>{let i=types.Tool().safeParse(s);if(!i.success)throw new provider.InvalidToolsError({info:"Invalid tools",cause:i.error});return i.data}).map(s=>({type:"function",function:s.definition.schema}))}}getCompleteChatUrl(e,t,o){return A(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,o){return A(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getCompleteChatData(e,t,o){return A(this,null,function*(){let s=this.transformConfig(e,t,o),i=this.transformMessages(t);if(i.messages&&i.messages.length===0)throw new provider.InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let m=o?this.transformTools(o):{};return new Promise(r=>{r(P(P(P(P({},this.getDefaultParams()),s),i),m));})})}transformCompleteChatResponse(e){let t=ln.safeParse(e);if(t.success){if(t.data.choices.length===0)throw new provider.ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(t.data)}`)});let o=t.data,s=[{role:types.AssistantRoleLiteral,content:[]}],i=o.choices[0].message;i.content&&s[0].content.push(types.createTextContent(i.content)),i.refusal&&s[0].content.push(types.createTextContent(i.refusal)),i.tool_calls&&i.tool_calls.forEach((g,_)=>{s[0].content.push(types.createToolCallContent(_,g.id,g.function.name,g.function.arguments));});let m={promptTokens:o.usage.prompt_tokens,completionTokens:o.usage.completion_tokens,totalTokens:o.usage.total_tokens},r=[],p=o.choices[0].logprobs;return p&&(p.content&&r.push(...p.content.map(g=>({token:g.token,logProb:g.logprob,bytes:g.bytes,topLogProbs:g.top_logprobs.map(_=>({token:_.token,logProb:_.logprob,bytes:_.bytes}))}))),p.refusal&&r.push(...p.refusal.map(g=>({token:g.token,logProb:g.logprob,bytes:g.bytes,topLogProbs:g.top_logprobs.map(_=>({token:_.token,logProb:_.logprob,bytes:_.bytes}))})))),{messages:s,usage:m,logProbs:r}}throw new provider.ModelResponseError({info:"Invalid response from model",cause:t.error})}getStreamChatUrl(e,t,o){return A(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getStreamChatHeaders(e,t,o){return A(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getStreamChatData(e,t,o){return A(this,null,function*(){let s=this.transformConfig(e,t,o),i=this.transformMessages(t);if(i.messages&&i.messages.length===0)throw new provider.InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let m=o?this.transformTools(o):{};return new Promise(r=>{r(P(P(P(P({stream:!0,stream_options:{include_usage:!0}},this.getDefaultParams()),s),i),m));})})}transformStreamChatResponseChunk(e,t){return no(this,null,function*(){var r,p;let o=t+e,s=[],i="",m=0;for(;m<o.length;){let g=o.indexOf(`
`,m);if(g===-1){i=o.substring(m);break}else {let _=o.substring(m,g).trim();_&&s.push(_),m=g+1;}}for(let g of s){if(g==="data: [DONE]")return;if(g.startsWith("data: ")){let _=g.substring(6);try{let b=JSON.parse(_),O=pn.safeParse(b);if(O.success){let C={partialMessages:[]},S=O.data;if(S.choices.length>0){let E=S.choices[0].delta;if(E!==void 0&&Object.keys(E).length!==0){if("content"in E&&E.content!==null)C.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,E.content));else if("refusal"in E&&E.refusal!==null)C.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,E.refusal));else if("tool_calls"in E&&E.tool_calls!==void 0){let D=E.tool_calls.at(0);C.partialMessages.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,D.index,D.id,(r=D.function)==null?void 0:r.name,(p=D.function)==null?void 0:p.arguments));}}}S.usage&&(C.usage={promptTokens:S.usage.prompt_tokens,completionTokens:S.usage.completion_tokens,totalTokens:S.usage.total_tokens}),yield {partialResponse:C,buffer:i};}else throw new provider.ModelResponseError({info:"Invalid response from model",cause:O.error})}catch(b){throw new provider.ModelResponseError({info:`Malformed JSON received in stream: ${_}`,cause:b})}}}yield {partialResponse:{partialMessages:[]},buffer:i};})}transformProxyStreamChatResponseChunk(e,t,o,s,i){return no(this,null,function*(){yield*dt(this.transformStreamChatResponseChunk(e,t));})}getProxyStreamChatUrl(e,t,o){return A(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getProxyCompleteChatUrl(e,t,o){return A(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getProxyCompleteChatHeaders(e,t,o){return A(this,null,function*(){if(!t)return {};let s=P({},t);return delete s.host,delete s["content-length"],s})}getProxyStreamChatHeaders(e,t,o){return A(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,t,o)})}getModelPricing(){if(!(this.modelName in T))throw new provider.ModelResponseError({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return T[this.modelName]}};var se="gpt-3.5-turbo-0125",hs="The latest GPT-3.5 Turbo model with higher accuracy at responding in requested formats and a fix for a bug which caused a text encoding issue for non-English language function calls. Training data up to Sept 2021.",go=provider.ChatModelSchema(h,x).parse({name:se,description:hs,maxInputTokens:4092,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.responseFormat(4092,4).def,schema:a.responseFormat(4092,4).schema},price:T[se]}),It=u,ie=class extends c{constructor(e){super(go,e);}};var ae="gpt-3.5-turbo-1106",_s="The latest GPT-3.5 Turbo model with improved instruction following, JSON mode, reproducible outputs, parallel function calling, and more. Returns a maximum of 4,096 output tokens. Training data up to Sept 2021.",To=provider.ChatModelSchema(h,x).parse({name:ae,description:_s,maxInputTokens:4092,maxOutputTokens:16385,roles:f,modalities:I,config:{def:a.responseFormat(16385,4).def,schema:a.responseFormat(16385,4).schema},price:T[ae]}),xt=u,re=class extends c{constructor(e){super(To,e);}};var le="gpt-3.5-turbo",Ts="Currently points to gpt-3.5-turbo-0125. Training data up to Sept 2021.",Mo=provider.ChatModelSchema(h,x).parse({name:le,description:Ts,maxInputTokens:4092,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.responseFormat(4092,4).def,schema:a.responseFormat(4092,4).schema},price:T[le]}),Rt=u,pe=class extends c{constructor(e){super(Mo,e);}};var me="gpt-4-0125-preview",ys="The latest GPT-4 model intended to reduce cases of \u201Claziness\u201D where the model doesn\u2019t complete a task. Training data up to Apr 2023.",yo=provider.ChatModelSchema(h,x).parse({name:me,description:ys,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.base(4092,4).def,schema:a.base(4092,4).schema},price:T[me]}),At=u,de=class extends c{constructor(e){super(yo,e);}};var ce="gpt-4-0613",Cs="Snapshot of gpt-4 from June 13th 2023 with improved function calling support. Training data up to Sept 2021.",Oo=provider.ChatModelSchema(h,x).parse({name:ce,description:Cs,maxInputTokens:8192,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.base(4092,4).def,schema:a.base(4092,4).schema},price:T[ce]}),Et=u,ue=class extends c{constructor(e){super(Oo,e);}};var he="gpt-4-1106-preview",Ps="GPT-4 Turbo model featuring improved instruction following, JSON mode, reproducible outputs, parallel function calling, and more. Returns a maximum of 4,096 output tokens. This preview model is not yet suited for production traffic. Training data up to Apr 2023.",Co=provider.ChatModelSchema(h,x).parse({name:he,description:Ps,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.base(4092,4).def,schema:a.base(4092,4).schema},price:T[he]}),Gt=u,fe=class extends c{constructor(e){super(Co,e);}};var _e="gpt-4.1",Is="Flagship model for complex tasks. It is well suited for problem solving across domains. Training data up to May 2024.",bo=provider.ChatModelSchema(h,y).parse({name:_e,description:Is,maxInputTokens:1047576,maxOutputTokens:32768,roles:f,modalities:M,config:{def:a.responseSchema(32768,4).def,schema:a.responseSchema(32768,4).schema},price:T[_e]}),kt=u,ge=class extends c{constructor(e){super(bo,e);}};var Te="gpt-4.1-mini",Rs="Provides a balance between intelligence, speed, and cost that makes it an attractive model for many use cases. Training data up to May 2024.",Po=provider.ChatModelSchema(h,y).parse({name:Te,description:Rs,maxInputTokens:1047576,maxOutputTokens:32768,roles:f,modalities:M,config:{def:a.responseSchema(32768,4).def,schema:a.responseSchema(32768,4).schema},price:T[Te]}),wt=u,Me=class extends c{constructor(e){super(Po,e);}};var ye="gpt-4.1-nano",Es="Fastest, most cost-effective GPT-4.1 model. Training data up to May 2024.",So=provider.ChatModelSchema(h,y).parse({name:ye,description:Es,maxInputTokens:1047576,maxOutputTokens:32768,roles:f,modalities:M,config:{def:a.responseSchema(32768,4).def,schema:a.responseSchema(32768,4).schema},price:T[ye]}),vt=u,Oe=class extends c{constructor(e){super(So,e);}};var Ce="gpt-4-turbo-2024-04-09",ks="GPT-4 Turbo with Vision model. Vision requests can now use JSON mode and function calling. gpt-4-turbo currently points to this version. Training data up to Dec 2023.",Io=provider.ChatModelSchema(h,y).parse({name:Ce,description:ks,maxInputTokens:128e3,maxOutputTokens:4096,roles:f,modalities:M,config:{def:a.responseFormat(4096,4).def,schema:a.responseFormat(4096,4).schema},price:T[Ce]}),qt=u,be=class extends c{constructor(e){super(Io,e);}};var Pe="gpt-4-turbo-preview",vs="Currently points to gpt-4-0125-preview. Training data up to Apr 2023.",xo=provider.ChatModelSchema(h,x).parse({name:Pe,description:vs,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.responseFormat(4092,4).def,schema:a.responseFormat(4092,4).schema},price:T[Pe]}),Dt=u,Se=class extends c{constructor(e){super(xo,e);}};var Ie="gpt-4-turbo",Ds="The latest GPT-4 Turbo model with vision capabilities. Vision requests can now use JSON mode and function calling. Currently points to gpt-4-turbo-2024-04-09. Training data up to Dec 2023.",Ro=provider.ChatModelSchema(h,y).parse({name:Ie,description:Ds,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:M,config:{def:a.responseFormat(4092,4).def,schema:a.responseFormat(4092,4).schema},price:T[Ie]}),Lt=u,xe=class extends c{constructor(e){super(Ro,e);}};var Re="gpt-4",Ns="Currently points to gpt-4-0613. Training data up to Sept 2021.",Ao=provider.ChatModelSchema(h,x).parse({name:Re,description:Ns,maxInputTokens:8192,maxOutputTokens:4092,roles:f,modalities:I,config:{def:a.base(4092,4).def,schema:a.base(4092,4).schema},price:T[Re]}),Nt=u,Ae=class extends c{constructor(e){super(Ao,e);}};var Ee="gpt-4o-2024-05-13",Bs="Latest snapshot of gpt-4o that supports Structured Outputs. Training data up to Oct 2023.",Eo=provider.ChatModelSchema(h,y).parse({name:Ee,description:Bs,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:M,config:{def:a.responseSchema(4092,4).def,schema:a.responseSchema(4092,4).schema},price:T[Ee]}),zt=u,Ge=class extends c{constructor(e){super(Eo,e);}};var ke="gpt-4o-2024-08-06",js="Latest snapshot of gpt-4o that supports Structured Outputs. Training data up to Oct 2023.",Go=provider.ChatModelSchema(h,y).parse({name:ke,description:js,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:M,config:{def:a.responseSchema(4092,4).def,schema:a.responseSchema(4092,4).schema},price:T[ke]}),Bt=u,we=class extends c{constructor(e){super(Go,e);}};var ve="gpt-4o-mini-2024-07-18",$s="Most advanced, multimodal flagship model that is cheaper and faster than GPT-4 Turbo. Currently points to gpt-4o-2024-05-13. Training data up to Oct 2023.",ko=provider.ChatModelSchema(h,y).parse({name:ve,description:$s,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:M,config:{def:a.responseSchema(4092,4).def,schema:a.responseSchema(4092,4).schema},price:T[ve]}),Ut=u,qe=class extends c{constructor(e){super(ko,e);}};var De="gpt-4o-mini",Vs="Most advanced, multimodal flagship model that is cheaper and faster than GPT-4 Turbo. Currently points to gpt-4o-2024-05-13. Training data up to Oct 2023.",wo=provider.ChatModelSchema(h,y).parse({name:De,description:Vs,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:M,config:{def:a.responseSchema(4092,4).def,schema:a.responseSchema(4092,4).schema},price:T[De]}),jt=u,Le=class extends c{constructor(e){super(wo,e);}};var Ne="gpt-4o",Js="Most advanced, multimodal flagship model that is cheaper and faster than GPT-4 Turbo. Currently points to gpt-4o-2024-05-13. Training data up to Oct 2023.",vo=provider.ChatModelSchema(h,y).parse({name:Ne,description:Js,maxInputTokens:128e3,maxOutputTokens:4092,roles:f,modalities:M,config:{def:a.responseSchema(4092,4).def,schema:a.responseSchema(4092,4).schema},price:T[Ne]}),Ft=u,ze=class extends c{constructor(e){super(vo,e);}};var Be="o1-2024-12-17",Ys="A stable release model for production use, offering robust performance and advanced features. Training data up to December 2024.",qo=provider.ChatModelSchema(h,y).parse({name:Be,description:Ys,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:M,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema},price:T[Be]}),$t=u,Ue=class extends c{constructor(e){super(qo,e);}};var je="o1",Xs="Highly capable general-purpose reasoning model with advanced capabilities in language, coding, and reasoning. Training data up to Oct 2023.",Do=provider.ChatModelSchema(h,y).parse({name:je,description:Xs,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:M,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema},price:T[je]}),Ht=u,Fe=class extends c{constructor(e){super(Do,e);}};var Lo="o3-2025-04-16",ei="A new standard for math, science, coding, and visual reasoning tasks. Training data up to Jun 2024.",No=provider.ChatModelSchema(h,y).parse({name:Lo,description:ei,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:M,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema}}),Vt=u,$e=class extends c{constructor(e){super(No,e);}};var zo="o3",ti="A new standard for math, science, coding, and visual reasoning tasks. Training data up to Jun 2024.",Bo=provider.ChatModelSchema(h,y).parse({name:zo,description:ti,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:M,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema}}),Kt=u,He=class extends c{constructor(e){super(Bo,e);}};var Uo="o3-mini",si="o3-mini is the newest small reasoning model, providing high intelligence at the same cost and latency targets of o1-mini. Training data up to Sep 2023.",jo=provider.ChatModelSchema(h,x).parse({name:Uo,description:si,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:I,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema}}),Jt=u,Ve=class extends c{constructor(e){super(jo,e);}};var Fo="o3-mini-2025-01-31",ai="o3-mini is the newest small reasoning model, providing high intelligence at the same cost and latency targets of o1-mini. Training data up to Sep 2023.",$o=provider.ChatModelSchema(h,x).parse({name:Fo,description:ai,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:I,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema}}),Wt=u,Ke=class extends c{constructor(e){super($o,e);}};var Ho="o4-mini-2025-04-16",li="Optimized for fast, effective reasoning with exceptionally efficient performance in coding and visual tasks. Training data up to Jun 2024.",Vo=provider.ChatModelSchema(h,y).parse({name:Ho,description:li,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:M,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema}}),Yt=u,Je=class extends c{constructor(e){super(Vo,e);}};var Ko="o4-mini",mi="Optimized for fast, effective reasoning with exceptionally efficient performance in coding and visual tasks. Training data up to Jun 2024.",Jo=provider.ChatModelSchema(h,y).parse({name:Ko,description:mi,maxInputTokens:2e5,maxOutputTokens:1e5,roles:f,modalities:M,config:{def:a.oSeries(1e5,4).def,schema:a.oSeries(1e5,4).schema}}),Qt=u,We=class extends c{constructor(e){super(Jo,e);}};var K=[types.EmbeddingTextModalityLiteral,types.EmbeddingTokenModalityLiteral],J=zod.z.enum([types.EmbeddingTextModalityLiteral,types.EmbeddingTokenModalityLiteral]);var _n=zod.z.object({object:zod.z.literal("list"),model:zod.z.string(),data:zod.z.array(zod.z.object({index:zod.z.number(),object:zod.z.literal("embedding"),embedding:zod.z.array(zod.z.number()).or(zod.z.string().base64())})),usage:zod.z.object({prompt_tokens:zod.z.number().nonnegative(),total_tokens:zod.z.number().nonnegative()})});var ci=zod.z.string().min(1).or(zod.z.array(zod.z.string().min(1)).min(1)).or(zod.z.array(zod.z.number().int().nonnegative()).min(1)).or(zod.z.array(zod.z.array(zod.z.number().int().nonnegative()).min(1)).min(1)),gn=zod.z.object({model:zod.z.string().min(1).optional(),input:ci,encoding_format:zod.z.enum(["float","base64"]).optional(),dimensions:zod.z.number().int().min(1).optional()});var j=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),getEmbeddingsUrl:zod.z.string().url().optional()}),N=class{constructor(e,t){this.version="v1";let o=j.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash(o.baseUrl||B.baseUrl),this.getEmbeddingsUrl=provider.urlWithoutTrailingSlash(o.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let t=r=>{let p=/(\d+)(h|m|s|ms)/g,g={h:36e5,m:6e4,s:1e3,ms:1},_,b=0;for(;(_=p.exec(r))!==null;){let O=parseInt(_[1]),C=_[2];b+=O*g[C];}return b},o=0,s=0,i=!0;e["x-ratelimit-reset-requests"]&&(o=t(e["x-ratelimit-reset-requests"])),e["x-ratelimit-reset-tokens"]&&(s=t(e["x-ratelimit-reset-tokens"]));let m=Math.max(o,s);return {shouldRetry:i,delayMs:m}}getTokenCount(e){return e.requests.reduce((t,o)=>t+o.length,0)}transformModelRequest(e){let t=gn.safeParse(e);if(!t.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model,i={encodingFormat:o.encoding_format,dimensions:o.dimensions},m=types.Config().parse(provider.removeUndefinedEntries(i)),r,p;return typeof o.input=="string"?p=types.EmbeddingTextModalityLiteral:typeof o.input[0]=="string"?p=types.EmbeddingTextModalityLiteral:p=types.EmbeddingTokenModalityLiteral,p===types.EmbeddingTextModalityLiteral?typeof o.input=="string"?r={modality:p,requests:[o.input]}:r={modality:p,requests:o.input}:typeof o.input[0]=="number"?r={modality:p,requests:[o.input]}:r={modality:p,requests:o.input},{modelName:s,config:m,embeddingRequests:r}}transformConfig(e,t){let o=this.modelSchema.config.schema.safeParse(e);if(!o.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:o.error});let s=o.data;return Object.keys(s).forEach(m=>{if(!this.modelSchema.config.def[m])throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${m}',
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((m,r)=>{let g=this.modelSchema.config.def[r].param,_=s[r];return m[g]=_,m},{})}transformEmbeddingRequests(e){let t=types.EmbeddingRequests().safeParse(e);if(!t.success)throw new provider.InvalidEmbeddingRequestsError({info:"Invalid embedding requests",cause:t.error});return {input:t.data.requests}}getGetEmbeddingsUrl(e,t){return A(this,null,function*(){return new Promise(o=>{o(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,t){return A(this,null,function*(){return new Promise(o=>{o(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,t){return A(this,null,function*(){return new Promise(o=>{o(P(P(P({},this.getDefaultParams()),this.transformConfig(e,t)),this.transformEmbeddingRequests(t)));})})}transformGetEmbeddingsResponse(e){let t,o=_n.safeParse(e);if(o.success){let s=o.data;t=typeof s.data[0].embedding=="string"?types.Base64EmbeddingLiteral:types.FloatEmbeddingLiteral;let i=s.data.map(m=>typeof m.embedding=="string"?{index:m.index,embedding:m.embedding}:{index:m.index,embedding:m.embedding});return {encodingFormat:t,embeddings:i,usage:{totalTokens:s.usage.total_tokens}}}throw new provider.ModelResponseError({info:"Invalid response from model",cause:o.error})}};var Wo="text-embedding-ada-002",bi="Most capable 2nd generation embedding model, replacing 16 first generation models",Yo=provider.EmbeddingModelSchema(J).parse({name:Wo,description:bi,modalities:K,maxInputTokens:8192,maxOutputTokens:1536,config:{def:v.base().def,schema:v.base().schema}}),Xt=j,Ye=class extends N{constructor(e){super(Yo,e);}};var Qo="text-embedding-3-small",Si="Increased performance over 2nd generation ada embedding model",Xo=provider.Embedd