@adaline/openai 0.14.0 → 0.15.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.d.mts +199 -57
- package/dist/index.d.ts +199 -57
- package/dist/index.js +131 -123
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +11 -11
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -2,19 +2,19 @@ import { z as z$1 } from 'zod';
|
|
|
2
2
|
import { RangeConfigItem, CHAT_CONFIG, SelectBooleanConfigItem, SelectStringConfigItem, ObjectSchemaConfigItem, ChatModelSchema, EmbeddingModelSchema, MultiStringConfigItem, urlWithoutTrailingSlash, InvalidModelRequestError, removeUndefinedEntries, getMimeTypeFromBase64, InvalidConfigError, InvalidMessagesError, InvalidToolsError, ModelResponseError, ModelError, InvalidEmbeddingRequestsError, ProviderError } from '@adaline/provider';
|
|
3
3
|
import { ResponseSchema, SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral, TextModalityLiteral, ImageModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral, EmbeddingTextModalityLiteral, EmbeddingTokenModalityLiteral, Config, Base64ImageContentTypeLiteral, UrlImageContentTypeLiteral, Message, Tool, createTextMessage, createToolCallMessage, EmbeddingRequests, Base64EmbeddingLiteral, FloatEmbeddingLiteral, createPartialTextMessage, createPartialToolCallMessage } from '@adaline/types';
|
|
4
4
|
|
|
5
|
-
var qt=Object.defineProperty,kt=Object.defineProperties;var Lt=Object.getOwnPropertyDescriptors;var Lo=Object.getOwnPropertySymbols;var jt=Object.prototype.hasOwnProperty,zt=Object.prototype.propertyIsEnumerable;var Bt=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var jo=(n,e,t)=>e in n?qt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,_=(n,e)=>{for(var t in e||(e={}))jt.call(e,t)&&jo(n,t,e[t]);if(Lo)for(var t of Lo(e))zt.call(e,t)&&jo(n,t,e[t]);return n},E=(n,e)=>kt(n,Lt(e));var I=(n,e,t)=>new Promise((o,s)=>{var a=l=>{try{i(t.next(l));}catch(c){s(c);}},p=l=>{try{i(t.throw(l));}catch(c){s(c);}},i=l=>l.done?o(l.value):Promise.resolve(l.value).then(a,p);i((t=t.apply(n,e)).next());}),Ft=function(n,e){this[0]=n,this[1]=e;},J=(n,e,t)=>{var o=(p,i,l,c)=>{try{var d=t[p](i),u=(i=d.value)instanceof Ft,f=d.done;Promise.resolve(u?i[0]:i).then(C=>u?o(p==="return"?p:"next",i[1]?{done:C.done,value:C.value}:C,l,c):l({value:C,done:f})).catch(C=>o("throw",C,l,c));}catch(C){c(C);}},s=p=>a[p]=i=>new Promise((l,c)=>o(p,i,l,c)),a={};return t=t.apply(n,e),a[Bt("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a};var qe=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),ke=n=>RangeConfigItem({param:"max_tokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),Le=n=>MultiStringConfigItem({param:"stop",title:CHAT_CONFIG.STOP(n).title,description:CHAT_CONFIG.STOP(n).description,max:n}),je=RangeConfigItem({param:"top_p",title:CHAT_CONFIG.TOP_P.title,description:CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),ze=RangeConfigItem({param:"frequency_penalty",title:CHAT_CONFIG.FREQUENCY_PENALTY.title,description:CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Be=RangeConfigItem({param:"presence_penalty",title:CHAT_CONFIG.PRESENCE_PENALTY.title,description:CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),Fe=RangeConfigItem({param:"seed",title:CHAT_CONFIG.SEED.title,description:CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),$e=SelectBooleanConfigItem({param:"logprobs",title:CHAT_CONFIG.LOG_PROBS.title,description:CHAT_CONFIG.LOG_PROBS.description,default:!1}),Ue=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}),De=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 B=(n,e)=>z$1.object({temperature:qe.schema,maxTokens:ke(n).schema,stop:Le(e).schema,topP:je.schema,frequencyPenalty:ze.schema,presencePenalty:Be.schema,seed:Fe.schema.transform(t=>t===0?void 0:t),logProbs:$e.schema,topLogProbs:Ue.schema,toolChoice:De.schema}),F=(n,e)=>({temperature:qe.def,maxTokens:ke(n).def,stop:Le(e).def,topP:je.def,frequencyPenalty:ze.def,presencePenalty:Be.def,seed:Fe.def,logProbs:$e.def,topLogProbs:Ue.def,toolChoice:De.def});var Bo=SelectStringConfigItem({param:"response_format",title:CHAT_CONFIG.RESPONSE_FORMAT.title,description:CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),Fo=(n,e)=>E(_({},F(n,e)),{responseFormat:Bo.def}),$o=(n,e)=>B(n,e).extend({responseFormat:Bo.schema});var Uo=ObjectSchemaConfigItem({param:"response_schema",title:CHAT_CONFIG.RESPONSE_SCHEMA.title,description:CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:ResponseSchema}),Do=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"]}),Y=(n,e)=>E(_({},F(n,e)),{responseFormat:Do.def,responseSchema:Uo.def}),X=(n,e)=>B(n,e).extend({responseFormat:Do.schema,responseSchema:Uo.schema});var Ho=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),Vo=n=>RangeConfigItem({param:"max_completion_tokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),Ko=(n,e)=>E(_({},Y(n,e)),{temperature:Ho.def,maxTokens:Vo(n).def}),Jo=(n,e)=>X(n,e).extend({temperature:Ho.schema,maxTokens:Vo(n).schema});var Ne=SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),He=n=>RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:n,step:1,default:n});var Z=()=>z$1.object({encodingFormat:Ne.schema}),ee=()=>({encodingFormat:Ne.def});var Wo=n=>Z().extend({dimensions:He(n).schema}),Yo=n=>E(_({},ee()),{dimensions:He(n).def});var h={base:(n,e)=>({def:F(n,e),schema:B(n,e)}),responseFormat:(n,e)=>({def:Fo(n,e),schema:$o(n,e)}),responseSchema:(n,e)=>({def:Y(n,e),schema:X(n,e)}),oSeries:(n,e)=>({def:Ko(n,e),schema:Jo(n,e)})},v={base:()=>({def:ee(),schema:Z()}),dimensions:n=>({def:Yo(n),schema:Wo(n)})};var y=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),b={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral},ne=z$1.enum([UserRoleLiteral,AssistantRoleLiteral]),se={user:UserRoleLiteral,assistant:AssistantRoleLiteral};var w=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],G=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),re=[TextModalityLiteral],le=z$1.enum([TextModalityLiteral]),S=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],P=z$1.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var pe=z$1.object({token:z$1.string(),logprob:z$1.number(),bytes:z$1.array(z$1.number()).nullable()}),ot=z$1.object({content:z$1.array(pe.extend({top_logprobs:z$1.array(pe)})).nullable(),refusal:z$1.array(pe.extend({top_logprobs:z$1.array(pe)})).nullable()}).nullable(),Qt=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()})})),tt=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:Qt.optional(),refusal:z$1.string().nullable().optional()}),logprobs:ot.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()})}),Zt=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()})),nt=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(),choices:z$1.array(z$1.object({index:z$1.number(),delta:z$1.object({content:z$1.string().nullable().optional(),tool_calls:Zt.optional(),refusal:z$1.string().nullable().optional()}).or(z$1.object({})),logprobs:ot,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 en=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()})}),on=z$1.enum(["none","auto","required"]),tn=z$1.object({type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1)})}),nn=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()})})),Ke=z$1.object({text:z$1.string().min(1),type:z$1.literal("text")}),sn=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()})}),an=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)})}),rn=z$1.object({role:z$1.literal("system"),content:z$1.string().min(1).or(z$1.array(Ke).min(1))}),ln=z$1.object({role:z$1.literal("user"),content:z$1.string().min(1).or(z$1.array(z$1.union([Ke,sn])).min(1))}),pn=z$1.object({role:z$1.literal("assistant"),content:z$1.string().min(1).or(z$1.array(Ke).min(1)).optional(),tool_calls:z$1.array(an).min(1).optional()}),mn=z$1.object({role:z$1.literal("tool"),tool_call_id:z$1.string().min(1),content:z$1.string().min(1)}),dn=z$1.union([rn,ln,pn,mn]),me=z$1.object({model:z$1.string().min(1).optional(),messages:z$1.array(dn).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_tokens:z$1.number().min(0).nullable().optional(),presence_penalty:z$1.number().min(-2).max(2).nullable().optional(),response_format:nn.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(en).optional(),tool_choice:on.or(tn).optional()});var st=me.omit({max_tokens:!0}).extend({max_completion_tokens:z$1.number().min(0).nullable().optional()});var g=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),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=g.parse(t);this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.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 _({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",source:"adaline.ai"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let t=i=>{let l=/(\d+)(h|m|s|ms)/g,c={h:36e5,m:6e4,s:1e3,ms:1},d,u=0;for(;(d=l.exec(i))!==null;){let f=parseInt(d[1]),C=d[2];u+=f*c[C];}return u},o=0,s=0,a=!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 p=Math.max(o,s);return {shouldRetry:a,delayMs:p}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let t=me.safeParse(e);if(!t.success)throw new 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 InvalidModelRequestError({info:`Invalid model request for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let a={};o.response_format&&(a.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(a.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"?a.toolChoice=o.tool_choice:a.toolChoice=o.tool_choice.function.name),a.seed=o.seed,a.maxTokens=o.max_tokens,a.temperature=o.temperature,a.topP=o.top_p,a.presencePenalty=o.presence_penalty,a.frequencyPenalty=o.frequency_penalty,a.stop=o.stop,a.logProbs=o.logprobs,a.topLogProbs=o.top_logprobs;let p=Config().parse(removeUndefinedEntries(a)),i=[],l={};o.messages.forEach(d=>{let u=d.role;switch(u){case"system":{let f=d.content;if(typeof f=="string")i.push({role:u,content:[{modality:TextModalityLiteral,value:f}]});else {let C=f.map(M=>({modality:TextModalityLiteral,value:M.text}));i.push({role:u,content:C});}}break;case"user":{let f=d.content;if(typeof f=="string")i.push({role:u,content:[{modality:TextModalityLiteral,value:f}]});else {let C=f.map(M=>M.type==="text"?{modality:TextModalityLiteral,value:M.text}:M.image_url.url.startsWith("data:")?{modality:ImageModalityLiteral,detail:M.image_url.detail||"auto",value:{type:Base64ImageContentTypeLiteral,base64:M.image_url.url,media_type:getMimeTypeFromBase64(M.image_url.url)}}:{modality:ImageModalityLiteral,detail:M.image_url.detail||"auto",value:{type:UrlImageContentTypeLiteral,url:M.image_url.url}});i.push({role:u,content:C});}}break;case"assistant":{let f=[];if(!d.content&&!d.tool_calls)throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelSchema.name}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(d.content){let C=d.content;typeof C=="string"?f.push({modality:TextModalityLiteral,value:C}):C.forEach(M=>{f.push({modality:TextModalityLiteral,value:M.text});});}d.tool_calls&&d.tool_calls.forEach((M,vt)=>{let ve={modality:ToolCallModalityLiteral,id:M.id,index:vt,name:M.function.name,arguments:M.function.arguments};f.push(ve),l[ve.id]=ve;}),i.push({role:u,content:f});}break;case"tool":{let f=d;i.push({role:u,content:[{modality:ToolResponseModalityLiteral,id:f.tool_call_id,index:l[f.tool_call_id].index,name:l[f.tool_call_id].name,data:f.content}]});}break}});let c=[];return o.tools&&o.tools.forEach(d=>{c.push({type:"function",definition:{schema:{name:d.function.name,description:d.function.description||"",strict:d.function.strict,parameters:d.function.parameters}}});}),{modelName:s,config:p,messages:i,tools:c.length>0?c:void 0}}transformConfig(e,t,o){let s=e.toolChoice;delete e.toolChoice;let a=this.modelSchema.config.schema.safeParse(e);if(!a.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:a.error});let p=a.data;s!==void 0&&(p.toolChoice=s),Object.keys(p).forEach(l=>{if(!(l in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${l}',
|
|
6
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let i=Object.keys(
|
|
7
|
-
one of [${
|
|
5
|
+
var Dt=Object.defineProperty,Ut=Object.defineProperties;var Nt=Object.getOwnPropertyDescriptors;var Do=Object.getOwnPropertySymbols;var Ht=Object.prototype.hasOwnProperty,Vt=Object.prototype.propertyIsEnumerable;var Kt=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n);var Uo=(n,e,t)=>e in n?Dt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,b=(n,e)=>{for(var t in e||(e={}))Ht.call(e,t)&&Uo(n,t,e[t]);if(Do)for(var t of Do(e))Vt.call(e,t)&&Uo(n,t,e[t]);return n},x=(n,e)=>Ut(n,Nt(e));var I=(n,e,t)=>new Promise((o,s)=>{var a=p=>{try{i(t.next(p));}catch(h){s(h);}},l=p=>{try{i(t.throw(p));}catch(h){s(h);}},i=p=>p.done?o(p.value):Promise.resolve(p.value).then(a,l);i((t=t.apply(n,e)).next());}),Jt=function(n,e){this[0]=n,this[1]=e;},J=(n,e,t)=>{var o=(l,i,p,h)=>{try{var d=t[l](i),T=(i=d.value)instanceof Jt,_=d.done;Promise.resolve(T?i[0]:i).then(C=>T?o(l==="return"?l:"next",i[1]?{done:C.done,value:C.value}:C,p,h):p({value:C,done:_})).catch(C=>o("throw",C,p,h));}catch(C){h(C);}},s=l=>a[l]=i=>new Promise((p,h)=>o(l,i,p,h)),a={};return t=t.apply(n,e),a[Kt("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a};var Le=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),je=n=>RangeConfigItem({param:"max_tokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),ze=n=>MultiStringConfigItem({param:"stop",title:CHAT_CONFIG.STOP(n).title,description:CHAT_CONFIG.STOP(n).description,max:n}),Be=RangeConfigItem({param:"top_p",title:CHAT_CONFIG.TOP_P.title,description:CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:1}),Fe=RangeConfigItem({param:"frequency_penalty",title:CHAT_CONFIG.FREQUENCY_PENALTY.title,description:CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),$e=RangeConfigItem({param:"presence_penalty",title:CHAT_CONFIG.PRESENCE_PENALTY.title,description:CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),De=RangeConfigItem({param:"seed",title:CHAT_CONFIG.SEED.title,description:CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),Ue=SelectBooleanConfigItem({param:"logprobs",title:CHAT_CONFIG.LOG_PROBS.title,description:CHAT_CONFIG.LOG_PROBS.description,default:!1}),Ne=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}),He=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 B=(n,e)=>z$1.object({temperature:Le.schema,maxTokens:je(n).schema,stop:ze(e).schema,topP:Be.schema,frequencyPenalty:Fe.schema,presencePenalty:$e.schema,seed:De.schema.transform(t=>t===0?void 0:t),logProbs:Ue.schema,topLogProbs:Ne.schema,toolChoice:He.schema}),F=(n,e)=>({temperature:Le.def,maxTokens:je(n).def,stop:ze(e).def,topP:Be.def,frequencyPenalty:Fe.def,presencePenalty:$e.def,seed:De.def,logProbs:Ue.def,topLogProbs:Ne.def,toolChoice:He.def});var Ho=SelectStringConfigItem({param:"response_format",title:CHAT_CONFIG.RESPONSE_FORMAT.title,description:CHAT_CONFIG.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]}),Vo=(n,e)=>x(b({},F(n,e)),{responseFormat:Ho.def}),Ko=(n,e)=>B(n,e).extend({responseFormat:Ho.schema});var Jo=ObjectSchemaConfigItem({param:"response_schema",title:CHAT_CONFIG.RESPONSE_SCHEMA.title,description:CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:ResponseSchema}),Wo=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"]}),Y=(n,e)=>x(b({},F(n,e)),{responseFormat:Wo.def,responseSchema:Jo.def}),X=(n,e)=>B(n,e).extend({responseFormat:Wo.schema,responseSchema:Jo.schema});var Xo=RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:1,max:1,step:.01,default:1}),Qo=n=>RangeConfigItem({param:"max_completion_tokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:n,step:1,default:0}),Zo=(n,e)=>x(b({},Y(n,e)),{temperature:Xo.def,maxTokens:Qo(n).def}),et=(n,e)=>X(n,e).extend({temperature:Xo.schema,maxTokens:Qo(n).schema});var Ve=SelectStringConfigItem({param:"encoding_format",title:"Encoding format",description:"Select the encoding format for the word embedding.",default:"float",choices:["float","base64"]}),Ke=n=>RangeConfigItem({param:"dimensions",title:"Dimensions",description:"Select the number of dimensions for the word embedding.",min:1,max:n,step:1,default:n});var Z=()=>z$1.object({encodingFormat:Ve.schema}),ee=()=>({encodingFormat:Ve.def});var ot=n=>Z().extend({dimensions:Ke(n).schema}),tt=n=>x(b({},ee()),{dimensions:Ke(n).def});var c={base:(n,e)=>({def:F(n,e),schema:B(n,e)}),responseFormat:(n,e)=>({def:Vo(n,e),schema:Ko(n,e)}),responseSchema:(n,e)=>({def:Y(n,e),schema:X(n,e)}),oSeries:(n,e)=>({def:Zo(n,e),schema:et(n,e)})},v={base:()=>({def:ee(),schema:Z()}),dimensions:n=>({def:tt(n),schema:ot(n)})};var g=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),y={system:SystemRoleLiteral,user:UserRoleLiteral,assistant:AssistantRoleLiteral,tool:ToolRoleLiteral},ne=z$1.enum([UserRoleLiteral,AssistantRoleLiteral]),se={user:UserRoleLiteral,assistant:AssistantRoleLiteral};var E=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],R=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),re=[TextModalityLiteral],pe=z$1.enum([TextModalityLiteral]),P=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],S=z$1.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var le=z$1.object({token:z$1.string(),logprob:z$1.number(),bytes:z$1.array(z$1.number()).nullable()}),rt=z$1.object({content:z$1.array(le.extend({top_logprobs:z$1.array(le)})).nullable().optional(),refusal:z$1.array(le.extend({top_logprobs:z$1.array(le)})).nullable().optional()}).nullable(),rn=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()})})),pt=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:rn.optional(),refusal:z$1.string().nullable().optional()}),logprobs:rt.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()})}),pn=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()})),lt=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(),choices:z$1.array(z$1.object({index:z$1.number(),delta:z$1.object({content:z$1.string().nullable().optional(),tool_calls:pn.optional(),refusal:z$1.string().nullable().optional()}).or(z$1.object({})),logprobs:rt,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 ln=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()})}),mn=z$1.enum(["none","auto","required"]),dn=z$1.object({type:z$1.literal("function"),function:z$1.object({name:z$1.string().min(1)})}),cn=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()})})),We=z$1.object({text:z$1.string().min(1),type:z$1.literal("text")}),hn=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()})}),un=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)})}),fn=z$1.object({role:z$1.literal("system"),content:z$1.string().min(1).or(z$1.array(We).min(1))}),Tn=z$1.object({role:z$1.literal("user"),content:z$1.string().min(1).or(z$1.array(z$1.union([We,hn])).min(1))}),_n=z$1.object({role:z$1.literal("assistant"),content:z$1.string().min(1).or(z$1.array(We).min(1)).optional(),tool_calls:z$1.array(un).min(1).optional()}),gn=z$1.object({role:z$1.literal("tool"),tool_call_id:z$1.string().min(1),content:z$1.string().min(1)}),yn=z$1.union([fn,Tn,_n,gn]),me=z$1.object({model:z$1.string().min(1).optional(),messages:z$1.array(yn).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_tokens:z$1.number().min(0).nullable().optional(),presence_penalty:z$1.number().min(-2).max(2).nullable().optional(),response_format:cn.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(ln).optional(),tool_choice:mn.or(dn).optional()});var mt=me.omit({max_tokens:!0}).extend({max_completion_tokens:z$1.number().min(0).nullable().optional()});var u=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),completeChatUrl:z$1.string().url().optional(),streamChatUrl:z$1.string().url().optional(),organization:z$1.string().optional()}),f=class{constructor(e,t){this.version="v1";let o=u.parse(t);this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.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 b({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",source:"adaline.ai"},this.organization?{"OpenAI-Organization":this.organization}:{})}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let t=i=>{let p=/(\d+)(h|m|s|ms)/g,h={h:36e5,m:6e4,s:1e3,ms:1},d,T=0;for(;(d=p.exec(i))!==null;){let _=parseInt(d[1]),C=d[2];T+=_*h[C];}return T},o=0,s=0,a=!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 l=Math.max(o,s);return {shouldRetry:a,delayMs:l}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let t=me.safeParse(e);if(!t.success)throw new 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 InvalidModelRequestError({info:`Invalid model request for model : '${this.modelSchema.name}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let a={};o.response_format&&(a.responseFormat=o.response_format.type,o.response_format.type==="json_schema"&&(a.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"?a.toolChoice=o.tool_choice:a.toolChoice=o.tool_choice.function.name),a.seed=o.seed,a.maxTokens=o.max_tokens,a.temperature=o.temperature,a.topP=o.top_p,a.presencePenalty=o.presence_penalty,a.frequencyPenalty=o.frequency_penalty,a.stop=o.stop,a.logProbs=o.logprobs,a.topLogProbs=o.top_logprobs;let l=Config().parse(removeUndefinedEntries(a)),i=[],p={};o.messages.forEach(d=>{let T=d.role;switch(T){case"system":{let _=d.content;if(typeof _=="string")i.push({role:T,content:[{modality:TextModalityLiteral,value:_}]});else {let C=_.map(M=>({modality:TextModalityLiteral,value:M.text}));i.push({role:T,content:C});}}break;case"user":{let _=d.content;if(typeof _=="string")i.push({role:T,content:[{modality:TextModalityLiteral,value:_}]});else {let C=_.map(M=>M.type==="text"?{modality:TextModalityLiteral,value:M.text}:M.image_url.url.startsWith("data:")?{modality:ImageModalityLiteral,detail:M.image_url.detail||"auto",value:{type:Base64ImageContentTypeLiteral,base64:M.image_url.url,media_type:getMimeTypeFromBase64(M.image_url.url)}}:{modality:ImageModalityLiteral,detail:M.image_url.detail||"auto",value:{type:UrlImageContentTypeLiteral,url:M.image_url.url}});i.push({role:T,content:C});}}break;case"assistant":{let _=[];if(!d.content&&!d.tool_calls)throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelSchema.name}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(d.content){let C=d.content;typeof C=="string"?_.push({modality:TextModalityLiteral,value:C}):C.forEach(M=>{_.push({modality:TextModalityLiteral,value:M.text});});}d.tool_calls&&d.tool_calls.forEach((M,$t)=>{let ke={modality:ToolCallModalityLiteral,id:M.id,index:$t,name:M.function.name,arguments:M.function.arguments};_.push(ke),p[ke.id]=ke;}),i.push({role:T,content:_});}break;case"tool":{let _=d;i.push({role:T,content:[{modality:ToolResponseModalityLiteral,id:_.tool_call_id,index:p[_.tool_call_id].index,name:p[_.tool_call_id].name,data:_.content}]});}break}});let h=[];return o.tools&&o.tools.forEach(d=>{h.push({type:"function",definition:{schema:{name:d.function.name,description:d.function.description||"",strict:d.function.strict,parameters:d.function.parameters}}});}),{modelName:s,config:l,messages:i,tools:h.length>0?h:void 0}}transformConfig(e,t,o){let s=e.toolChoice;delete e.toolChoice;let a=this.modelSchema.config.schema.safeParse(e);if(!a.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:a.error});let l=a.data;s!==void 0&&(l.toolChoice=s),Object.keys(l).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${p}',
|
|
6
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let i=Object.keys(l).reduce((p,h)=>{let d=this.modelSchema.config.def[h],T=d.param,_=l[h];return T==="max_tokens"&&d.type==="range"&&_===0?p[T]=d.max:p[T]=_,p},{});if(i.top_logprobs&&!i.logprobs)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in i&&i.tool_choice!==void 0){let p=i.tool_choice;if(!o||o&&o.length===0)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,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(p))if(o.map(d=>d.definition.schema.name).includes(p))i.tool_choice={type:"function",function:{name:p}};else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`toolChoice : '${p}' is not part of provided 'tools' names or
|
|
7
|
+
one of [${h.choices.join(", ")}]`)})}}if("response_format"in i&&i.response_format!==void 0){let p=i.response_format;if(p==="json_schema")if("response_schema"in i)i.response_format={type:"json_schema",json_schema:i.response_schema},delete i.response_schema;else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else i.response_format={type:p};}return i}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=e.map(s=>{let a=Message().safeParse(s);if(!a.success)throw new InvalidMessagesError({info:"Invalid messages",cause:a.error});return a.data});return t.forEach(s=>{s.content.forEach(a=>{if(!this.modelSchema.modalities.includes(a.modality))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support modality : '${a.modality}',
|
|
8
8
|
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(s=>{if(!Object.keys(this.modelSchema.roles).includes(s.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support role : '${s.role}',
|
|
9
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),{messages:t.map(s=>{switch(s.role){case SystemRoleLiteral:{let a=[];return s.content.forEach(
|
|
10
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(e){if(!this.modelSchema.modalities.includes(ToolCallModalityLiteral))throw new InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(s=>{let a=Tool().safeParse(s);if(!a.success)throw new InvalidToolsError({info:"Invalid tools",cause:a.error});return a.data}).map(s=>({type:"function",function:s.definition.schema}))}}getCompleteChatUrl(e,t,o){return I(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,o){return I(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getCompleteChatData(e,t,o){return I(this,null,function*(){let s=this.transformConfig(e,t,o),a=this.transformMessages(t);if(a.messages&&a.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let
|
|
11
|
-
`).filter(p=>p.trim()!=="");for(let p of o){if(p==="data: [DONE]")return;if(p.startsWith("data: {")&&p.endsWith("}")){let i;try{i=JSON.parse(p.substring(6));}catch(c){throw new ModelResponseError({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${i}`)})}let l=nt.safeParse(i);if(l.success){let c={partialMessages:[]},d=l.data;if(d.choices.length>0){let u=d.choices[0].delta;if(u!==void 0&&Object.keys(u).length!==0){if("content"in u&&u.content!==null)c.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,u.content));else if("refusal"in u&&u.refusal!==null)c.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,u.refusal));else if("tool_calls"in u&&u.tool_calls!==void 0){let f=u.tool_calls.at(0);c.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,f.index,f.id,(s=f.function)==null?void 0:s.name,(a=f.function)==null?void 0:a.arguments));}}}d.usage&&(c.usage={promptTokens:d.usage.prompt_tokens,completionTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens}),yield {partialResponse:c,buffer:t};}else throw new ModelResponseError({info:"Invalid response from model",cause:l.error})}}})}};var N=class extends T{constructor(e,t){super(e,t);}transformModelRequest(e){let t=st.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=E(_({},o),{max_tokens:o.max_completion_tokens});return delete s.max_completion_tokens,super.transformModelRequest(s)}transformTools(e){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support 'tools'.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support 'tools'.`)})}getStreamChatUrl(e,t,o){return I(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}getStreamChatHeaders(e,t,o){return I(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}getStreamChatData(e,t,o){return I(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}transformStreamChatResponseChunk(e,t){return J(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}};var Qe="gpt-3.5-turbo-0125",En="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.",Ze=ChatModelSchema(y,P).parse({name:Qe,description:En,maxInputTokens:4092,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.responseFormat(4092,4).def,schema:h.responseFormat(4092,4).schema}}),lt=g,he=class extends T{constructor(e){super(Ze,e);}};var eo="gpt-3.5-turbo-1106",xn="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.",oo=ChatModelSchema(y,P).parse({name:eo,description:xn,maxInputTokens:4092,maxOutputTokens:16385,roles:b,modalities:S,config:{def:h.responseFormat(16385,4).def,schema:h.responseFormat(16385,4).schema}}),pt=g,ue=class extends T{constructor(e){super(oo,e);}};var to="gpt-3.5-turbo",wn="Currently points to gpt-3.5-turbo-0125. Training data up to Sept 2021.",no=ChatModelSchema(y,P).parse({name:to,description:wn,maxInputTokens:4092,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.responseFormat(4092,4).def,schema:h.responseFormat(4092,4).schema}}),mt=g,fe=class extends T{constructor(e){super(no,e);}};var so="gpt-4-0125-preview",vn="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.",ao=ChatModelSchema(y,P).parse({name:so,description:vn,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.base(4092,4).def,schema:h.base(4092,4).schema}}),dt=g,ge=class extends T{constructor(e){super(ao,e);}};var io="gpt-4-0613",kn="Snapshot of gpt-4 from June 13th 2023 with improved function calling support. Training data up to Sept 2021.",ro=ChatModelSchema(y,P).parse({name:io,description:kn,maxInputTokens:8192,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.base(4092,4).def,schema:h.base(4092,4).schema}}),ct=g,Te=class extends T{constructor(e){super(ro,e);}};var lo="gpt-4-1106-preview",jn="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.",po=ChatModelSchema(y,P).parse({name:lo,description:jn,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.base(4092,4).def,schema:h.base(4092,4).schema}}),ht=g,_e=class extends T{constructor(e){super(po,e);}};var mo="gpt-4-turbo-2024-04-09",Bn="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.",co=ChatModelSchema(y,G).parse({name:mo,description:Bn,maxInputTokens:128e3,maxOutputTokens:4096,roles:b,modalities:w,config:{def:h.responseFormat(4096,4).def,schema:h.responseFormat(4096,4).schema}}),ut=g,ye=class extends T{constructor(e){super(co,e);}};var ho="gpt-4-turbo-preview",$n="Currently points to gpt-4-0125-preview. Training data up to Apr 2023.",uo=ChatModelSchema(y,P).parse({name:ho,description:$n,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.responseFormat(4092,4).def,schema:h.responseFormat(4092,4).schema}}),ft=g,be=class extends T{constructor(e){super(uo,e);}};var fo="gpt-4-turbo",Dn="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.",go=ChatModelSchema(y,G).parse({name:fo,description:Dn,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:w,config:{def:h.responseFormat(4092,4).def,schema:h.responseFormat(4092,4).schema}}),gt=g,Ce=class extends T{constructor(e){super(go,e);}};var To="gpt-4",Hn="Currently points to gpt-4-0613. Training data up to Sept 2021.",_o=ChatModelSchema(y,P).parse({name:To,description:Hn,maxInputTokens:8192,maxOutputTokens:4092,roles:b,modalities:S,config:{def:h.base(4092,4).def,schema:h.base(4092,4).schema}}),Tt=g,Oe=class extends T{constructor(e){super(_o,e);}};var yo="gpt-4o-2024-08-06",Kn="Latest snapshot of gpt-4o that supports Structured Outputs. Training data up to Oct 2023.",bo=ChatModelSchema(y,G).parse({name:yo,description:Kn,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:w,config:{def:h.responseSchema(4092,4).def,schema:h.responseSchema(4092,4).schema}}),_t=g,Me=class extends T{constructor(e){super(bo,e);}};var Co="gpt-4o-mini",Wn="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.",Oo=ChatModelSchema(y,G).parse({name:Co,description:Wn,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:w,config:{def:h.responseSchema(4092,4).def,schema:h.responseSchema(4092,4).schema}}),yt=g,Se=class extends T{constructor(e){super(Oo,e);}};var Mo="gpt-4o",Xn="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.",So=ChatModelSchema(y,G).parse({name:Mo,description:Xn,maxInputTokens:128e3,maxOutputTokens:4092,roles:b,modalities:w,config:{def:h.responseFormat(4092,4).def,schema:h.responseFormat(4092,4).schema}}),bt=g,Pe=class extends T{constructor(e){super(So,e);}};var Po="o1-mini",Zn="Faster and cheaper reasoning model particularly good at coding, math, and science. Training data up to Oct 2023.",Io=ChatModelSchema(ne,le).parse({name:Po,description:Zn,maxInputTokens:128e3,maxOutputTokens:4092,roles:se,modalities:re,config:{def:h.oSeries(4092,4).def,schema:h.oSeries(4092,4).schema}}),Ct=g,Ie=class extends N{constructor(e){super(Io,e);}};var Eo="o1-preview",os="Reasoning model designed to solve hard problems across domains. Training data up to Oct 2023.",Ro=ChatModelSchema(ne,le).parse({name:Eo,description:os,maxInputTokens:128e3,maxOutputTokens:4092,roles:se,modalities:re,config:{def:h.oSeries(4092,4).def,schema:h.oSeries(4092,4).schema}}),Ot=g,Ee=class extends N{constructor(e){super(Ro,e);}};var H=[EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral],V=z$1.enum([EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral]);var Pt=z$1.object({object:z$1.literal("list"),model:z$1.string(),data:z$1.array(z$1.object({index:z$1.number(),object:z$1.literal("embedding"),embedding:z$1.array(z$1.number()).or(z$1.string().base64())})),usage:z$1.object({prompt_tokens:z$1.number().nonnegative(),total_tokens:z$1.number().nonnegative()})});var ns=z$1.string().min(1).or(z$1.array(z$1.string().min(1)).min(1)).or(z$1.array(z$1.number().int().nonnegative()).min(1)).or(z$1.array(z$1.array(z$1.number().int().nonnegative()).min(1)).min(1)),It=z$1.object({model:z$1.string().min(1).optional(),input:ns,encoding_format:z$1.enum(["float","base64"]).optional(),dimensions:z$1.number().int().min(1).optional()});var z=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),getEmbeddingsUrl:z$1.string().url().optional()}),k=class{constructor(e,t){this.version="v1";let o=z.parse(t);this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(o.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",source:"adaline.ai"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let t=i=>{let l=/(\d+)(h|m|s|ms)/g,c={h:36e5,m:6e4,s:1e3,ms:1},d,u=0;for(;(d=l.exec(i))!==null;){let f=parseInt(d[1]),C=d[2];u+=f*c[C];}return u},o=0,s=0,a=!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 p=Math.max(o,s);return {shouldRetry:a,delayMs:p}}getTokenCount(e){return e.requests.reduce((t,o)=>t+o.length,0)}transformModelRequest(e){let t=It.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model,a={encodingFormat:o.encoding_format,dimensions:o.dimensions},p=Config().parse(removeUndefinedEntries(a)),i,l;return typeof o.input=="string"?l=EmbeddingTextModalityLiteral:typeof o.input[0]=="string"?l=EmbeddingTextModalityLiteral:l=EmbeddingTokenModalityLiteral,l===EmbeddingTextModalityLiteral?typeof o.input=="string"?i={modality:l,requests:[o.input]}:i={modality:l,requests:o.input}:typeof o.input[0]=="number"?i={modality:l,requests:[o.input]}:i={modality:l,requests:o.input},{modelName:s,config:p,embeddingRequests:i}}transformConfig(e,t){let o=this.modelSchema.config.schema.safeParse(e);if(!o.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:o.error});let s=o.data;return Object.keys(s).forEach(p=>{if(!this.modelSchema.config.def[p])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${p}',
|
|
12
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((
|
|
13
|
-
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[e].model,s=
|
|
14
|
-
[${this.chatModelLiterals().join(", ")}]`)});return this.chatModelFactories[e].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(e,t){var
|
|
15
|
-
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[e].model,s=
|
|
9
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),{messages:t.map(s=>{switch(s.role){case SystemRoleLiteral:{let a=[];return s.content.forEach(l=>{if(l.modality===TextModalityLiteral)a.push({type:"text",text:l.value});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${l.modality}'`)})}),{role:this.modelSchema.roles[s.role],content:a}}case AssistantRoleLiteral:{let a=[],l=[];return s.content.forEach(i=>{if(i.modality===TextModalityLiteral)a.push({type:"text",text:i.value});else if(i.modality===ToolCallModalityLiteral)l.push({id:i.id,type:"function",function:{name:i.name,arguments:i.arguments}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${i.modality}'`)})}),b({role:this.modelSchema.roles[s.role],content:a},l.length>0?{tool_calls:l}:{})}case UserRoleLiteral:{let a=[],l=[];s.content.forEach(p=>{if(p.modality===TextModalityLiteral)a.push({type:"text",text:p.value});else if(p.modality===ImageModalityLiteral)l.push({type:"image_url",image_url:{url:p.value.type==="url"?p.value.url:p.value.base64,detail:p.detail}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' cannot have content with modality : '${p.modality}'`)})});let i=[...a,...l];return {role:this.modelSchema.roles[s.role],content:i}}case ToolRoleLiteral:{if(s.content.length!==1)throw new 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!==ToolResponseModalityLiteral)throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' must have content with modality : '${ToolResponseModalityLiteral}'`)});let a=s.content[0];return {role:this.modelSchema.roles[s.role],tool_call_id:a.id,content:a.data}}default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`role : '${s.role}' is not supported,
|
|
10
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(e){if(!this.modelSchema.modalities.includes(ToolCallModalityLiteral))throw new InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(s=>{let a=Tool().safeParse(s);if(!a.success)throw new InvalidToolsError({info:"Invalid tools",cause:a.error});return a.data}).map(s=>({type:"function",function:s.definition.schema}))}}getCompleteChatUrl(e,t,o){return I(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,o){return I(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getCompleteChatData(e,t,o){return I(this,null,function*(){let s=this.transformConfig(e,t,o),a=this.transformMessages(t);if(a.messages&&a.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let l=o?this.transformTools(o):{};return new Promise(i=>{i(b(b(b(b({},this.getDefaultParams()),s),a),l));})})}transformCompleteChatResponse(e){let t=pt.safeParse(e);if(t.success){if(t.data.choices.length===0)throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(t.data)}`)});let o=t.data,s=[],a=o.choices[0].message;a.content&&s.push(createTextMessage(AssistantRoleLiteral,a.content)),a.refusal&&s.push(createTextMessage(AssistantRoleLiteral,a.refusal)),a.tool_calls&&a.tool_calls.forEach((h,d)=>{s.push(createToolCallMessage(AssistantRoleLiteral,d,h.id,h.function.name,h.function.arguments));});let l={promptTokens:o.usage.prompt_tokens,completionTokens:o.usage.completion_tokens,totalTokens:o.usage.total_tokens},i=[],p=o.choices[0].logprobs;return p&&(p.content&&i.push(...p.content.map(h=>({token:h.token,logProb:h.logprob,bytes:h.bytes,topLogProbs:h.top_logprobs.map(d=>({token:d.token,logProb:d.logprob,bytes:d.bytes}))}))),p.refusal&&i.push(...p.refusal.map(h=>({token:h.token,logProb:h.logprob,bytes:h.bytes,topLogProbs:h.top_logprobs.map(d=>({token:d.token,logProb:d.logprob,bytes:d.bytes}))})))),{messages:s,usage:l,logProbs:i}}throw new ModelResponseError({info:"Invalid response from model",cause:t.error})}getStreamChatUrl(e,t,o){return I(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getStreamChatHeaders(e,t,o){return I(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getStreamChatData(e,t,o){return I(this,null,function*(){let s=this.transformConfig(e,t,o),a=this.transformMessages(t);if(a.messages&&a.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let l=o?this.transformTools(o):{};return new Promise(i=>{i(b(b(b(b({stream:!0,stream_options:{include_usage:!0}},this.getDefaultParams()),s),a),l));})})}transformStreamChatResponseChunk(e,t){return J(this,null,function*(){var s,a;let o=(t+e).split(`
|
|
11
|
+
`).filter(l=>l.trim()!=="");for(let l of o){if(l==="data: [DONE]")return;if(l.startsWith("data: {")&&l.endsWith("}")){let i;try{i=JSON.parse(l.substring(6));}catch(h){throw new ModelResponseError({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${i}`)})}let p=lt.safeParse(i);if(p.success){let h={partialMessages:[]},d=p.data;if(d.choices.length>0){let T=d.choices[0].delta;if(T!==void 0&&Object.keys(T).length!==0){if("content"in T&&T.content!==null)h.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,T.content));else if("refusal"in T&&T.refusal!==null)h.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,T.refusal));else if("tool_calls"in T&&T.tool_calls!==void 0){let _=T.tool_calls.at(0);h.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,_.index,_.id,(s=_.function)==null?void 0:s.name,(a=_.function)==null?void 0:a.arguments));}}}d.usage&&(h.usage={promptTokens:d.usage.prompt_tokens,completionTokens:d.usage.completion_tokens,totalTokens:d.usage.total_tokens}),yield {partialResponse:h,buffer:t};}else throw new ModelResponseError({info:"Invalid response from model",cause:p.error})}}})}};var N=class extends f{constructor(e,t){super(e,t);}transformModelRequest(e){let t=mt.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=x(b({},o),{max_tokens:o.max_completion_tokens});return delete s.max_completion_tokens,super.transformModelRequest(s)}transformTools(e){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support 'tools'.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support 'tools'.`)})}getStreamChatUrl(e,t,o){return I(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}getStreamChatHeaders(e,t,o){return I(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}getStreamChatData(e,t,o){return I(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}transformStreamChatResponseChunk(e,t){return J(this,null,function*(){throw new ModelError({info:`Model: '${this.modelSchema.name}' does not support streaming.`,cause:new Error(`Model: '${this.modelSchema.name}' does not support streaming.`)})})}};var eo="gpt-3.5-turbo-0125",kn="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.",oo=ChatModelSchema(g,S).parse({name:eo,description:kn,maxInputTokens:4092,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.responseFormat(4092,4).def,schema:c.responseFormat(4092,4).schema}}),ut=u,he=class extends f{constructor(e){super(oo,e);}};var to="gpt-3.5-turbo-1106",jn="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.",no=ChatModelSchema(g,S).parse({name:to,description:jn,maxInputTokens:4092,maxOutputTokens:16385,roles:y,modalities:P,config:{def:c.responseFormat(16385,4).def,schema:c.responseFormat(16385,4).schema}}),ft=u,ue=class extends f{constructor(e){super(no,e);}};var so="gpt-3.5-turbo",Bn="Currently points to gpt-3.5-turbo-0125. Training data up to Sept 2021.",ao=ChatModelSchema(g,S).parse({name:so,description:Bn,maxInputTokens:4092,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.responseFormat(4092,4).def,schema:c.responseFormat(4092,4).schema}}),Tt=u,fe=class extends f{constructor(e){super(ao,e);}};var io="gpt-4-0125-preview",$n="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.",ro=ChatModelSchema(g,S).parse({name:io,description:$n,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.base(4092,4).def,schema:c.base(4092,4).schema}}),_t=u,Te=class extends f{constructor(e){super(ro,e);}};var po="gpt-4-0613",Un="Snapshot of gpt-4 from June 13th 2023 with improved function calling support. Training data up to Sept 2021.",lo=ChatModelSchema(g,S).parse({name:po,description:Un,maxInputTokens:8192,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.base(4092,4).def,schema:c.base(4092,4).schema}}),gt=u,_e=class extends f{constructor(e){super(lo,e);}};var mo="gpt-4-1106-preview",Hn="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=ChatModelSchema(g,S).parse({name:mo,description:Hn,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.base(4092,4).def,schema:c.base(4092,4).schema}}),yt=u,ge=class extends f{constructor(e){super(co,e);}};var ho="gpt-4-turbo-2024-04-09",Kn="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.",uo=ChatModelSchema(g,R).parse({name:ho,description:Kn,maxInputTokens:128e3,maxOutputTokens:4096,roles:y,modalities:E,config:{def:c.responseFormat(4096,4).def,schema:c.responseFormat(4096,4).schema}}),bt=u,ye=class extends f{constructor(e){super(uo,e);}};var fo="gpt-4-turbo-preview",Wn="Currently points to gpt-4-0125-preview. Training data up to Apr 2023.",To=ChatModelSchema(g,S).parse({name:fo,description:Wn,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.responseFormat(4092,4).def,schema:c.responseFormat(4092,4).schema}}),Ct=u,be=class extends f{constructor(e){super(To,e);}};var _o="gpt-4-turbo",Xn="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.",go=ChatModelSchema(g,R).parse({name:_o,description:Xn,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:E,config:{def:c.responseFormat(4092,4).def,schema:c.responseFormat(4092,4).schema}}),Ot=u,Ce=class extends f{constructor(e){super(go,e);}};var yo="gpt-4",Zn="Currently points to gpt-4-0613. Training data up to Sept 2021.",bo=ChatModelSchema(g,S).parse({name:yo,description:Zn,maxInputTokens:8192,maxOutputTokens:4092,roles:y,modalities:P,config:{def:c.base(4092,4).def,schema:c.base(4092,4).schema}}),Mt=u,Oe=class extends f{constructor(e){super(bo,e);}};var Co="gpt-4o-2024-08-06",os="Latest snapshot of gpt-4o that supports Structured Outputs. Training data up to Oct 2023.",Oo=ChatModelSchema(g,R).parse({name:Co,description:os,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:E,config:{def:c.responseSchema(4092,4).def,schema:c.responseSchema(4092,4).schema}}),Pt=u,Me=class extends f{constructor(e){super(Oo,e);}};var Mo="gpt-4o-mini",ns="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.",Po=ChatModelSchema(g,R).parse({name:Mo,description:ns,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:E,config:{def:c.responseSchema(4092,4).def,schema:c.responseSchema(4092,4).schema}}),St=u,Pe=class extends f{constructor(e){super(Po,e);}};var So="gpt-4o",as="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.",Io=ChatModelSchema(g,R).parse({name:So,description:as,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:E,config:{def:c.responseFormat(4092,4).def,schema:c.responseFormat(4092,4).schema}}),It=u,Se=class extends f{constructor(e){super(Io,e);}};var Eo="gpt-4o-mini-2024-07-18",rs="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.",Ro=ChatModelSchema(g,R).parse({name:Eo,description:rs,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:E,config:{def:c.responseSchema(4092,4).def,schema:c.responseSchema(4092,4).schema}}),Et=u,Ie=class extends f{constructor(e){super(Ro,e);}};var xo="gpt-4o-2024-05-13",ls="Latest snapshot of gpt-4o that supports Structured Outputs. Training data up to Oct 2023.",Ao=ChatModelSchema(g,R).parse({name:xo,description:ls,maxInputTokens:128e3,maxOutputTokens:4092,roles:y,modalities:E,config:{def:c.responseSchema(4092,4).def,schema:c.responseSchema(4092,4).schema}}),Rt=u,Ee=class extends f{constructor(e){super(Ao,e);}};var wo="o1-mini",ds="Faster and cheaper reasoning model particularly good at coding, math, and science. Training data up to Oct 2023.",Go=ChatModelSchema(ne,pe).parse({name:wo,description:ds,maxInputTokens:128e3,maxOutputTokens:4092,roles:se,modalities:re,config:{def:c.oSeries(4092,4).def,schema:c.oSeries(4092,4).schema}}),xt=u,Re=class extends N{constructor(e){super(Go,e);}};var vo="o1-preview",hs="Reasoning model designed to solve hard problems across domains. Training data up to Oct 2023.",qo=ChatModelSchema(ne,pe).parse({name:vo,description:hs,maxInputTokens:128e3,maxOutputTokens:4092,roles:se,modalities:re,config:{def:c.oSeries(4092,4).def,schema:c.oSeries(4092,4).schema}}),At=u,xe=class extends N{constructor(e){super(qo,e);}};var H=[EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral],V=z$1.enum([EmbeddingTextModalityLiteral,EmbeddingTokenModalityLiteral]);var vt=z$1.object({object:z$1.literal("list"),model:z$1.string(),data:z$1.array(z$1.object({index:z$1.number(),object:z$1.literal("embedding"),embedding:z$1.array(z$1.number()).or(z$1.string().base64())})),usage:z$1.object({prompt_tokens:z$1.number().nonnegative(),total_tokens:z$1.number().nonnegative()})});var fs=z$1.string().min(1).or(z$1.array(z$1.string().min(1)).min(1)).or(z$1.array(z$1.number().int().nonnegative()).min(1)).or(z$1.array(z$1.array(z$1.number().int().nonnegative()).min(1)).min(1)),qt=z$1.object({model:z$1.string().min(1).optional(),input:fs,encoding_format:z$1.enum(["float","base64"]).optional(),dimensions:z$1.number().int().min(1).optional()});var z=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),getEmbeddingsUrl:z$1.string().url().optional()}),k=class{constructor(e,t){this.version="v1";let o=z.parse(t);this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(o.getEmbeddingsUrl||`${this.baseUrl}/embeddings`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",source:"adaline.ai"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){let t=i=>{let p=/(\d+)(h|m|s|ms)/g,h={h:36e5,m:6e4,s:1e3,ms:1},d,T=0;for(;(d=p.exec(i))!==null;){let _=parseInt(d[1]),C=d[2];T+=_*h[C];}return T},o=0,s=0,a=!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 l=Math.max(o,s);return {shouldRetry:a,delayMs:l}}getTokenCount(e){return e.requests.reduce((t,o)=>t+o.length,0)}transformModelRequest(e){let t=qt.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model,a={encodingFormat:o.encoding_format,dimensions:o.dimensions},l=Config().parse(removeUndefinedEntries(a)),i,p;return typeof o.input=="string"?p=EmbeddingTextModalityLiteral:typeof o.input[0]=="string"?p=EmbeddingTextModalityLiteral:p=EmbeddingTokenModalityLiteral,p===EmbeddingTextModalityLiteral?typeof o.input=="string"?i={modality:p,requests:[o.input]}:i={modality:p,requests:o.input}:typeof o.input[0]=="number"?i={modality:p,requests:[o.input]}:i={modality:p,requests:o.input},{modelName:s,config:l,embeddingRequests:i}}transformConfig(e,t){let o=this.modelSchema.config.schema.safeParse(e);if(!o.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:o.error});let s=o.data;return Object.keys(s).forEach(l=>{if(!this.modelSchema.config.def[l])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${l}',
|
|
12
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((l,i)=>{let h=this.modelSchema.config.def[i].param,d=s[i];return l[h]=d,l},{})}transformEmbeddingRequests(e){let t=EmbeddingRequests().safeParse(e);if(!t.success)throw new InvalidEmbeddingRequestsError({info:"Invalid embedding requests",cause:t.error});return {input:t.data.requests}}getGetEmbeddingsUrl(e,t){return I(this,null,function*(){return new Promise(o=>{o(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,t){return I(this,null,function*(){return new Promise(o=>{o(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,t){return I(this,null,function*(){return new Promise(o=>{o(b(b(b({},this.getDefaultParams()),this.transformConfig(e,t)),this.transformEmbeddingRequests(t)));})})}transformGetEmbeddingsResponse(e){let t,o=vt.safeParse(e);if(o.success){let s=o.data;t=typeof s.data[0].embedding=="string"?Base64EmbeddingLiteral:FloatEmbeddingLiteral;let a=s.data.map(l=>typeof l.embedding=="string"?{index:l.index,embedding:l.embedding}:{index:l.index,embedding:l.embedding});return {encodingFormat:t,embeddings:a,usage:{totalTokens:s.usage.total_tokens}}}throw new ModelResponseError({info:"Invalid response from model",cause:o.error})}};var Lo="text-embedding-ada-002",Is="Most capable 2nd generation embedding model, replacing 16 first generation models",jo=EmbeddingModelSchema(V).parse({name:Lo,description:Is,modalities:H,maxInputTokens:8192,maxOutputTokens:1536,config:{def:v.base().def,schema:v.base().schema}}),jt=z,we=class extends k{constructor(e){super(jo,e);}};var zo="text-embedding-3-small",Rs="Increased performance over 2nd generation ada embedding model",Bo=EmbeddingModelSchema(V).parse({name:zo,description:Rs,modalities:H,maxInputTokens:8192,maxOutputTokens:1536,config:{def:v.dimensions(1536).def,schema:v.dimensions(1536).schema}}),zt=z,Ge=class extends k{constructor(e){super(Bo,e);}};var Fo="text-embedding-3-large",As="Most capable embedding model for both english and non-english tasks",$o=EmbeddingModelSchema(V).parse({name:Fo,description:As,modalities:H,maxInputTokens:8192,maxOutputTokens:3072,config:{def:v.dimensions(3072).def,schema:v.dimensions(3072).schema}}),Bt=z,ve=class extends k{constructor(e){super($o,e);}};var ws="openai",Ft=class{constructor(){this.version="v1";this.name=ws;this.baseUrl="https://api.openai.com/v1";this.chatModelFactories={[so]:{model:fe,modelOptions:Tt,modelSchema:ao},[eo]:{model:he,modelOptions:ut,modelSchema:oo},[to]:{model:ue,modelOptions:ft,modelSchema:no},[io]:{model:Te,modelOptions:_t,modelSchema:ro},[po]:{model:_e,modelOptions:gt,modelSchema:lo},[mo]:{model:ge,modelOptions:yt,modelSchema:co},[ho]:{model:ye,modelOptions:bt,modelSchema:uo},[fo]:{model:be,modelOptions:Ct,modelSchema:To},[_o]:{model:Ce,modelOptions:Ot,modelSchema:go},[yo]:{model:Oe,modelOptions:Mt,modelSchema:bo},[Co]:{model:Me,modelOptions:Pt,modelSchema:Oo},[Mo]:{model:Pe,modelOptions:St,modelSchema:Po},[So]:{model:Se,modelOptions:It,modelSchema:Io},[Eo]:{model:Ie,modelOptions:Et,modelSchema:Ro},[xo]:{model:Ee,modelOptions:Rt,modelSchema:Ao},[wo]:{model:Re,modelOptions:xt,modelSchema:Go},[vo]:{model:xe,modelOptions:At,modelSchema:qo}};this.embeddingModelFactories={[Lo]:{model:we,modelOptions:jt,modelSchema:jo},[zo]:{model:Ge,modelOptions:zt,modelSchema:Bo},[Fo]:{model:ve,modelOptions:Bt,modelSchema:$o}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModel(e,t){var l;if(!(e in this.chatModelFactories))throw new ProviderError({info:`OpenAI chat model: ${e} not found`,cause:new Error(`OpenAI chat model: ${e} not found, available chat models:
|
|
13
|
+
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[e].model,s=x(b({},t),{baseUrl:(l=t.baseUrl)!=null?l:this.baseUrl}),a=this.chatModelFactories[e].modelOptions.parse(s);return new o(a)}chatModelSchema(e){if(!(e in this.chatModelFactories))throw new ProviderError({info:`OpenAI chat model: ${e} not found `,cause:new Error(`OpenAI chat model: ${e} not found, available chat models:
|
|
14
|
+
[${this.chatModelLiterals().join(", ")}]`)});return this.chatModelFactories[e].modelSchema}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModel(e,t){var l;if(!(e in this.embeddingModelFactories))throw new ProviderError({info:`OpenAI embedding model: ${e} not found`,cause:new Error(`OpenAI embedding model: ${e} not found, available embedding models:
|
|
15
|
+
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[e].model,s=x(b({},t),{baseUrl:(l=t.baseUrl)!=null?l:this.baseUrl}),a=this.embeddingModelFactories[e].modelOptions.parse(s);return new o(a)}embeddingModelSchema(e){if(!(e in this.embeddingModelFactories))throw new ProviderError({info:`OpenAI embedding model: ${e} not found`,cause:new Error(`OpenAI embedding model: ${e} not found, available embedding models:
|
|
16
16
|
[${this.embeddingModelLiterals().join(", ")}]`)});return this.embeddingModelFactories[e].modelSchema}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,t)=>(e[t]=this.embeddingModelFactories[t].modelSchema,e),{})}};
|
|
17
17
|
|
|
18
|
-
export {
|
|
18
|
+
export { f as BaseChatModel, u as BaseChatModelOptions, k as BaseEmbeddingModel, z as BaseEmbeddingModelOptions, N as BaseOSeriesChatModel, F as ChatModelBaseConfigDef, B as ChatModelBaseConfigSchema, Zo as ChatModelOSeriesConfigDef, et as ChatModelOSeriesConfigSchema, Vo as ChatModelResponseFormatConfigDef, Ko as ChatModelResponseFormatConfigSchema, Y as ChatModelResponseSchemaConfigDef, X as ChatModelResponseSchemaConfigSchema, ee as EmbeddingModelBaseConfigDef, Z as EmbeddingModelBaseConfigSchema, tt as EmbeddingModelDimensionsConfigDef, ot as EmbeddingModelDimensionsConfigSchema, fe as GPT_3_5_Turbo, so as GPT_3_5_TurboLiteral, Tt as GPT_3_5_TurboOptions, ao as GPT_3_5_TurboSchema, he as GPT_3_5_Turbo_0125, eo as GPT_3_5_Turbo_0125Literal, ut as GPT_3_5_Turbo_0125Options, oo as GPT_3_5_Turbo_0125Schema, ue as GPT_3_5_Turbo_1106, to as GPT_3_5_Turbo_1106Literal, ft as GPT_3_5_Turbo_1106Options, no as GPT_3_5_Turbo_1106Schema, Oe as GPT_4, yo as GPT_4Literal, Mt as GPT_4Options, bo as GPT_4Schema, Te as GPT_4_0125_Preview, io as GPT_4_0125_PreviewLiteral, _t as GPT_4_0125_PreviewOptions, ro as GPT_4_0125_PreviewSchema, _e as GPT_4_0613, po as GPT_4_0613Literal, gt as GPT_4_0613Options, lo as GPT_4_0613Schema, ge as GPT_4_1106_Preview, mo as GPT_4_1106_PreviewLiteral, yt as GPT_4_1106_PreviewOptions, co as GPT_4_1106_PreviewSchema, Ce as GPT_4_Turbo, _o as GPT_4_TurboLiteral, Ot as GPT_4_TurboOptions, go as GPT_4_TurboSchema, ye as GPT_4_Turbo_2024_04_09, ho as GPT_4_Turbo_2024_04_09Literal, bt as GPT_4_Turbo_2024_04_09Options, uo as GPT_4_Turbo_2024_04_09Schema, be as GPT_4_Turbo_Preview, fo as GPT_4_Turbo_PreviewLiteral, Ct as GPT_4_Turbo_PreviewOptions, To as GPT_4_Turbo_PreviewSchema, Se as GPT_4o, So as GPT_4oLiteral, It as GPT_4oOptions, Io as GPT_4oSchema, Ee as GPT_4o_2024_05_13, xo as GPT_4o_2024_05_13Literal, Rt as GPT_4o_2024_05_13Options, Ao as GPT_4o_2024_05_13Schema, Me as GPT_4o_2024_08_06, Co as GPT_4o_2024_08_06Literal, Pt as GPT_4o_2024_08_06Options, Oo as GPT_4o_2024_08_06Schema, Pe as GPT_4o_Mini, Mo as GPT_4o_MiniLiteral, St as GPT_4o_MiniOptions, Po as GPT_4o_MiniSchema, Ie as GPT_4o_Mini_2024_07_18, Eo as GPT_4o_Mini_2024_07_18Literal, Et as GPT_4o_Mini_2024_07_18Options, Ro as GPT_4o_Mini_2024_07_18Schema, Re as O1_Mini, wo as O1_MiniLiteral, xt as O1_MiniOptions, Go as O1_MiniSchema, xe as O1_Preview, vo as O1_PreviewLiteral, At as O1_PreviewOptions, qo as O1_PreviewSchema, Ft as OpenAI, c as OpenAIChatModelConfigs, E as OpenAIChatModelModalities, R as OpenAIChatModelModalitiesEnum, ne as OpenAIChatModelOSSeriesRoles, se as OpenAIChatModelOSSeriesRolesMap, g as OpenAIChatModelRoles, y as OpenAIChatModelRolesMap, re as OpenAIChatModelTextModalities, pe as OpenAIChatModelTextModalitiesEnum, P as OpenAIChatModelTextToolModalities, S as OpenAIChatModelTextToolModalitiesEnum, mt as OpenAIChatOSeriesRequest, me as OpenAIChatRequest, _n as OpenAIChatRequestAssistantMessage, hn as OpenAIChatRequestImageContent, yn as OpenAIChatRequestMessage, cn as OpenAIChatRequestResponseFormat, fn as OpenAIChatRequestSystemMessage, We as OpenAIChatRequestTextContent, ln as OpenAIChatRequestTool, un as OpenAIChatRequestToolCallContent, mn as OpenAIChatRequestToolChoiceEnum, dn as OpenAIChatRequestToolChoiceFunction, gn as OpenAIChatRequestToolMessage, Tn as OpenAIChatRequestUserMessage, pt as OpenAICompleteChatResponse, v as OpenAIEmbeddingModelConfigs, H as OpenAIEmbeddingModelModalities, V as OpenAIEmbeddingModelModalitiesEnum, qt as OpenAIEmbeddingRequest, fs as OpenAIEmbeddingRequestInput, vt as OpenAIGetEmbeddingsResponse, lt as OpenAIStreamChatResponse, rn as OpenAIToolCallsCompleteChatResponse, pn as OpenAIToolCallsStreamChatResponse, ws as ProviderLiteral, ve as Text_Embedding_3_Large, Fo as Text_Embedding_3_LargeLiteral, $o as Text_Embedding_3_LargeSchema, Bt as Text_Embedding_3_Large_Options, Ge as Text_Embedding_3_Small, zo as Text_Embedding_3_SmallLiteral, Bo as Text_Embedding_3_SmallSchema, zt as Text_Embedding_3_Small_Options, we as Text_Embedding_Ada002, Lo as Text_Embedding_Ada002Literal, jo as Text_Embedding_Ada002Schema, jt as Text_Embedding_Ada002_Options, Ke as dimensions, Ve as encodingFormat, Fe as frequencyPenalty, Ue as logProbs, je as maxTokens, $e as presencePenalty, De as seed, ze as stop, Le as temperature, He as toolChoice, Ne as topLogProbs, Be as topP };
|
|
19
19
|
//# sourceMappingURL=index.mjs.map
|
|
20
20
|
//# sourceMappingURL=index.mjs.map
|