@adaline/open-router 0.1.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.js ADDED
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ var bt=Object.defineProperty;var Ce=Object.getOwnPropertySymbols;var Ct=Object.prototype.hasOwnProperty,Tt=Object.prototype.propertyIsEnumerable;var Rt=(o,t)=>(t=Symbol[o])?t:Symbol.for("Symbol."+o);var Te=(o,t,n)=>t in o?bt(o,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[t]=n,R=(o,t)=>{for(var n in t||(t={}))Ct.call(t,n)&&Te(o,n,t[n]);if(Ce)for(var n of Ce(t))Tt.call(t,n)&&Te(o,n,t[n]);return o};var P=(o,t,n)=>new Promise((a,r)=>{var s=c=>{try{p(n.next(c));}catch(h){r(h);}},d=c=>{try{p(n.throw(c));}catch(h){r(h);}},p=c=>c.done?a(c.value):Promise.resolve(c.value).then(s,d);p((n=n.apply(o,t)).next());}),vt=function(o,t){this[0]=o,this[1]=t;},Re=(o,t,n)=>{var a=(d,p,c,h)=>{try{var u=n[d](p),y=(p=u.value)instanceof vt,g=u.done;Promise.resolve(y?p[0]:p).then(b=>y?a(d==="return"?d:"next",p[1]?{done:b.done,value:b.value}:b,c,h):c({value:b,done:g})).catch(b=>a("throw",b,c,h));}catch(b){h(b);}},r=d=>s[d]=p=>new Promise((c,h)=>a(d,p,c,h)),s={};return n=n.apply(o,t),s[Rt("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var Ot=o=>{let t=new WeakSet;return JSON.stringify(o,(n,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return;t.add(a);}return a})},Mt=o=>o==null?"unknown error":typeof o=="string"?o:o instanceof Error?o.message:Ot(o),H="GatewayBaseError",w=class Ee extends Error{constructor({info:t,cause:n},a){super(`[${a!=null?a:H}]: ${t}
6
+ Message: ${Mt(n)}`),this.name=H,this.info=t,this.cause=n,this.name=a!=null?a:H,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof Ee}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},I="system",k="user",v="assistant",q="tool",Et=[I,k,v,q],G=zod.z.enum(Et),xt=[v],_t=zod.z.enum(xt),x="image",Y="base64",Pt=["png","jpeg","webp","gif"],wt=zod.z.object({type:zod.z.literal(Y),base64:zod.z.string(),media_type:zod.z.enum(Pt)}),V="url",St=zod.z.object({type:zod.z.literal(V),url:zod.z.string()}),jt=zod.z.discriminatedUnion("type",[wt,St]),It=["low","medium","high","auto"],kt=zod.z.enum(It),qt=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(x),detail:kt,value:jt,metadata:o}),T="text",xe=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(T),value:zod.z.string(),metadata:o}),J="partial-text",_e=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(J),value:zod.z.string(),metadata:o}),E="tool-call",Pe=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(E),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:o}),W="partial-tool-call",we=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(W),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:o}),_="tool-response",Lt=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(_),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:o}),Nt=[T,x,E,_],Se=zod.z.enum(Nt),Ut=(o=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[xe(o),qt(t),Pe(n),Lt(a)]),$t=[J,W];zod.z.enum($t);var Bt=(o=zod.z.undefined(),t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[_e(o),we(t)]);var L=(o=G,t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined(),r=zod.z.undefined(),s=zod.z.undefined())=>zod.z.object({role:o,content:zod.z.array(Ut(t,n,a,r)),metadata:s}),Z=(o=_t,t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined())=>zod.z.object({role:o,partialContent:Bt(t,n),metadata:a});var Q=(o,t)=>L().parse({role:o,content:[xe().parse({modality:T,value:t})]});var je=(o,t,n,a,r)=>L().parse({role:o,content:[Pe().parse({modality:E,index:t,id:n,name:a,arguments:r})]});var X=(o,t)=>Z().parse({role:o,partialContent:_e().parse({modality:J,value:t})}),Ie=(o,t,n,a,r)=>Z().parse({role:o,partialContent:we().parse({modality:W,index:t,id:n,name:a,arguments:r})});var ke=(o=zod.z.record(zod.z.string(),zod.z.any()).optional())=>o,At=["object","array","number","string","boolean","enum"],ve=zod.z.enum(At),Ft=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([ve,zod.z.array(zod.z.union([ve,zod.z.literal("null")]))]).optional(),default:zod.z.any().optional(),title:zod.z.string().optional(),description:zod.z.string().max(4096).optional(),properties:zod.z.record(zod.z.any()).optional(),required:zod.z.array(zod.z.string()).optional(),minItems:zod.z.number().int().min(0).optional(),maxItems:zod.z.number().int().optional(),items:zod.z.record(zod.z.any()).optional(),enum:zod.z.array(zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()])).optional(),minimum:zod.z.number().optional(),maximum:zod.z.number().optional(),minLength:zod.z.number().int().min(0).optional(),maxLength:zod.z.number().int().optional(),$ref:zod.z.string().optional()}),zt=zod.z.object({type:zod.z.enum(["object"]),required:zod.z.array(zod.z.string()),$defs:zod.z.record(zod.z.any()).optional(),properties:zod.z.record(Ft),additionalProperties:zod.z.literal(!1)});zod.z.object({name:zod.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:zod.z.string().max(4096),strict:zod.z.boolean().optional(),schema:zt}).optional();var Dt="function";var Kt=zod.z.enum(["object","array","number","string","boolean","null"]),Ht=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:Kt.optional(),default:zod.z.any().optional(),title:zod.z.string().optional(),description:zod.z.string().max(4096).optional(),properties:zod.z.record(zod.z.any()).optional(),required:zod.z.array(zod.z.string()).optional(),minItems:zod.z.number().int().min(0).optional(),maxItems:zod.z.number().int().optional(),items:zod.z.record(zod.z.any()).optional(),enum:zod.z.array(zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()])).optional(),minimum:zod.z.number().optional(),maximum:zod.z.number().optional(),minLength:zod.z.number().int().min(0).optional(),maxLength:zod.z.number().int().optional()});zod.z.object({type:zod.z.enum(["object"]),title:zod.z.string().optional(),$defs:zod.z.record(zod.z.any()).optional(),properties:zod.z.record(Ht).optional(),required:zod.z.array(zod.z.string()).optional()});var Gt=zod.z.object({name:zod.z.string().regex(/^[a-zA-Z0-9_]{1,64}$/).max(64),description:zod.z.string().max(4096),parameters:zod.z.any(),strict:zod.z.boolean().optional()});var Yt=zod.z.enum(["function"]),Vt=zod.z.object({type:Yt,definition:zod.z.object({schema:Gt})}),Jt=[Dt];zod.z.enum(Jt);var qe=(o=zod.z.undefined())=>zod.z.discriminatedUnion("type",[Vt.extend({metadata:o})]),Wt="text",Zt="token",Qt=[Wt,Zt];zod.z.enum(Qt);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var eo="float",to=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),oo="base64",no=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),Oe=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(eo),embeddings:zod.z.array(to),usage:Oe.optional()}),zod.z.object({encodingFormat:zod.z.literal(oo),embeddings:zod.z.array(no),usage:Oe.optional()})]);var Le=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Me=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),ao=Me.extend({topLogProbs:zod.z.array(Me)}),Ne=zod.z.array(ao);zod.z.object({messages:zod.z.array(L()),usage:Le.optional(),logProbs:Ne.optional()});zod.z.object({partialMessages:zod.z.array(Z()),usage:Le.optional(),logProbs:Ne.optional()});var so=Object.defineProperty,Ue=Object.getOwnPropertySymbols,ro=Object.prototype.hasOwnProperty,io=Object.prototype.propertyIsEnumerable,$e=(o,t,n)=>t in o?so(o,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[t]=n,B=(o,t)=>{for(var n in t||(t={}))ro.call(t,n)&&$e(o,n,t[n]);if(Ue)for(var n of Ue(t))io.call(t,n)&&$e(o,n,t[n]);return o},Be="ProviderError",S=class He extends w{constructor({info:t,cause:n}){super({info:t,cause:n},Be),this.name=Be,this.info=t,this.cause=n;}static isProviderError(t){return t instanceof He}};var Ae="ModelResponseError",N=class Ge extends w{constructor({info:t,cause:n}){super({info:t,cause:n},Ae),this.name=Ae,this.cause=n,this.info=t;}static isModelResponseError(t){return t instanceof Ge}},Fe="InvalidModelRequestError",A=class Ye extends w{constructor({info:t,cause:n}){super({info:t,cause:n},Fe),this.name=Fe,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(t){return t instanceof Ye}},ze="InvalidConfigError",j=class Ve extends w{constructor({info:t,cause:n}){super({info:t,cause:n},ze),this.name=ze,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(t){return t instanceof Ve}},De="InvalidMessagesError",O=class Je extends w{constructor({info:t,cause:n}){super({info:t,cause:n},De),this.name=De,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(t){return t instanceof Je}},Ke="InvalidToolsError",ee=class We extends w{constructor({info:t,cause:n}){super({info:t,cause:n},Ke),this.name=Ke,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof We}};var te="multi-string",Ze=zod.z.object({type:zod.z.literal(te),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),max:zod.z.number().int().positive()}),lo=o=>zod.z.array(zod.z.string()).max(o).default([]).optional(),Qe=o=>({def:Ze.parse(B({type:te},o)),schema:lo(o.max)}),oe="range",Xe=zod.z.object({type:zod.z.literal(oe),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),min:zod.z.number().int(),max:zod.z.number().int(),step:zod.z.number().positive(),default:zod.z.number()}),po=(o,t,n,a)=>zod.z.number().min(o).max(t).step(n).default(a).optional(),M=o=>({def:Xe.parse(B({type:oe},o)),schema:po(o.min,o.max,o.step,o.default)}),ne="select-string",et=zod.z.object({type:zod.z.literal(ne),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string().min(1).nullable(),choices:zod.z.array(zod.z.string().min(1))}),mo=(o,t)=>zod.z.enum(t).nullable().default(o).optional(),ae=o=>({def:et.parse(B({type:ne},o)),schema:mo(o.default,o.choices)}),tt="object-schema",co=zod.z.object({type:zod.z.literal(tt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),objectSchema:zod.z.any()});var se="select-boolean",ot=zod.z.object({type:zod.z.literal(se),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.boolean().nullable()}),uo=o=>zod.z.boolean().nullable().default(o).optional(),nt=o=>({def:ot.parse(B({type:se},o)),schema:uo(o.default)}),ho=[oe,te,ne,tt,se];zod.z.enum(ho);var fo=zod.z.discriminatedUnion("type",[Xe,Ze,et,ot,co]),at=(o=G,t=Se)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(o,zod.z.string().min(1).optional()),modalities:zod.z.array(t).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),fo),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(n=>{var a,r;let s=Object.keys(n.def),d=Object.keys((r=(a=n.schema)==null?void 0:a.shape)!=null?r:{});return s.every(p=>d.includes(p))&&d.every(p=>s.includes(p))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})});zod.z.record(zod.z.string());zod.z.record(zod.z.union([zod.z.boolean(),zod.z.string(),zod.z.number(),zod.z.object({}),zod.z.array(zod.z.any()),zod.z.null(),zod.z.undefined()]));zod.z.string().url();var go={type:"range",title:"Temperature",description:"Adjusts the model's creativity level. With a setting of 0, the model strictly picks the most probable next word. For endeavors that benefit from a dash of inventiveness, consider dialing it up to 0.7 or higher, enabling the model to produce text that's unexpectedly fresh."},yo={type:"range",title:"Max tokens",description:"Specify the total tokens for generation, where one token approximates four English characters. Setting this to 0 defaults to the model's maximum capacity."},bo=o=>({type:"multi",title:"Stop sequence",description:`Enter up to ${o} sequences that will halt additional text output. The generated text will exclude these sequences.`}),Co={type:"range",title:"Top A",description:"Considers only the top tokens that have 'sufficiently high' probabilities relative to the most likely token, functioning like a dynamic Top-P. A lower Top-A value narrows down the token choices based on the highest probability token, while a higher Top-A value refines the filtering without necessarily impacting the creativity of the output."},To={type:"range",title:"Top P",description:"Selects a subset of likely tokens for generation, restricting choices to the top-P fraction of possibilities, such as the top 10% when P=0.1. This approach can limit the variety of the output. By default, it's set to 1, indicating no restriction. It's advised to adjust this parameter or temperature to modulate output diversity, but not to modify both simultaneously."},Ro={type:"range",title:"Top K",description:"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options."},vo={type:"range",title:"Min P",description:"Specifies the minimum probability a token must have to be considered, in relation to the probability of the most likely token. (This value varies based on the confidence level of the top token.) For example, if Min-P is set to 0.1, only tokens with at least 1/10th the probability of the highest-ranked token will be considered."},Oo={type:"range",title:"Frequency penalty",description:"Minimize redundancy. By assigning a penalty to frequently used tokens within the text, the likelihood of repeating identical phrases is reduced. The default setting for this penalty is zero."},Mo={type:"range",title:"Presence penalty",description:"Enhance the introduction of novel subjects by reducing the preference for tokens that have already appeared in the text, thus boosting the chances of exploring fresh topics. The standard setting for this is zero."},Eo={type:"range",title:"Seed",description:"When seed is fixed to a specific value, the model makes a best effort to provide the same response for repeated requests. Deterministic output isn't guaranteed. Also, changing the model or parameter settings, such as the temperature, can cause variations in the response even when you use the same seed value. By default, a random seed value is used."},xo={type:"range",title:"Repetition penalty",description:"Reduces the likelihood of repeating tokens from the input. Increasing this value makes the model less prone to repetition, but setting it too high may lead to less coherent output, often resulting in run-on sentences missing smaller words. The token penalty is scaled according to the original token's probability."},_o={type:"boolean",title:"Log probs",description:"Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned."},Po={type:"range",title:"Top log probs",description:"The number of most likely tokens to return at each token position, each with an associated log probability. 'logprobs' must be set to true if this parameter is used."},wo={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},So={type:"select",title:"Response format",description:"Choose the response format of your model. For JSON, you must include the string 'JSON' in some form within your system / user prompt."},jo={type:"select",title:"Response format",description:"Choose the response format of your model. 'json_object' colloquially known as JSON mode, instructs the model to respond with a valid JSON (must include the term 'json' in prompt). 'json_schema' colloquially known as structured outputs, allows you to specify a strict response schema that the model will adhere to."},Io={type:"object",title:"Response schema",description:"When response format is set to 'json_schema', the model will return a JSON object of the specified schema."},f={TEMPERATURE:go,MAX_TOKENS:yo,STOP:bo,TOP_A:Co,TOP_P:To,TOP_K:Ro,MIN_P:vo,FREQUENCY_PENALTY:Oo,PRESENCE_PENALTY:Mo,REPETITION_PENALTY:xo,SEED:Eo,LOG_PROBS:_o,TOP_LOG_PROBS:Po,ECHO:wo,RESPONSE_FORMAT:So,RESPONSE_FORMAT_WITH_SCHEMA:jo,RESPONSE_SCHEMA:Io};var st=o=>Object.fromEntries(Object.entries(o).filter(([t,n])=>n!=null));var rt=o=>o.split(";")[0].split("/")[1],F=o=>o==null?void 0:o.replace(/\/$/,"");var re=M({param:"temperature",title:f.TEMPERATURE.title,description:f.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),ie=o=>M({param:"max_tokens",title:f.MAX_TOKENS.title,description:f.MAX_TOKENS.description,min:0,max:o,step:1,default:0}),le=o=>Qe({param:"stop",title:f.STOP(o).title,description:f.STOP(o).description,max:o}),bn=M({param:"top_a",title:f.TOP_A.title,description:f.TOP_A.description,min:0,max:1,step:.01,default:0}),Cn=M({param:"top_k",title:f.TOP_K.title,description:f.TOP_K.description,min:0,max:100,step:1,default:0}),pe=M({param:"top_p",title:f.TOP_P.title,description:f.TOP_P.description,min:0,max:1,step:.01,default:1}),Tn=M({param:"min_p",title:f.MIN_P.title,description:f.MIN_P.description,min:0,max:1,step:.01,default:0}),me=M({param:"frequency_penalty",title:f.FREQUENCY_PENALTY.title,description:f.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),ce=M({param:"presence_penalty",title:f.PRESENCE_PENALTY.title,description:f.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),Rn=M({param:"repetition_penalty",title:f.REPETITION_PENALTY.title,description:f.REPETITION_PENALTY.description,min:0,max:2,step:.01,default:0}),de=M({param:"seed",title:f.SEED.title,description:f.SEED.description,min:0,max:1e6,step:1,default:0}),ue=nt({param:"logprobs",title:f.LOG_PROBS.title,description:f.LOG_PROBS.description,default:!1}),he=M({param:"top_logprobs",title:f.TOP_LOG_PROBS.title,description:f.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),fe=ae({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"]}),vn=ae({param:"response_format",title:f.RESPONSE_FORMAT.title,description:f.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]});var it=(o,t)=>zod.z.object({temperature:re.schema,maxTokens:ie(o).schema,stop:le(t).schema,topP:pe.schema,frequencyPenalty:me.schema,presencePenalty:ce.schema,seed:de.schema.transform(n=>n===0?void 0:n),logProbs:ue.schema,topLogProbs:he.schema,toolChoice:fe.schema}),lt=(o,t)=>({temperature:re.def,maxTokens:ie(o).def,stop:le(t).def,topP:pe.def,frequencyPenalty:me.def,presencePenalty:ce.def,seed:de.def,logProbs:ue.def,topLogProbs:he.def,toolChoice:fe.def});var ge={base:(o,t)=>({def:lt(o,t),schema:it(o,t)})};var qo="open-router",U=class{constructor(){this.version="v1";this.name=qo;}chatModelLiterals(){throw new S({info:"Not implemented",cause:new Error("Not implemented")})}chatModel(t,n){let a=R({modelName:t},n);return new z(ye,a)}chatModelSchema(t){return ye}chatModelSchemas(){throw new S({info:"Not implemented",cause:new Error("Not implemented")})}embeddingModelLiterals(){throw new S({info:"Open Router does not support embedding models",cause:new Error("Open Router does not support embedding models")})}embeddingModel(t,n){throw new S({info:"Open Router does not support embedding models",cause:new Error("Open Router does not support embedding models")})}embeddingModelSchema(t){throw new S({info:"Open Router does not support embedding models",cause:new Error("Open Router does not support embedding models")})}embeddingModelSchemas(){throw new S({info:"Open Router does not support embedding models",cause:new Error("Open Router does not support embedding models")})}};U.baseUrl="https://openrouter.ai/api/v1";var pt=zod.z.enum([I,k,v,q]),mt={system:I,user:k,assistant:v,tool:q};var ct=[T,x,E,_],dt=zod.z.enum([T,x,E,_]);var D=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),ut=zod.z.object({content:zod.z.array(D.extend({top_logprobs:zod.z.array(D)})).nullable(),refusal:zod.z.array(D.extend({top_logprobs:zod.z.array(D)})).nullable()}).nullable(),Uo=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()})})),ht=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().optional(),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:Uo.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:ut.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()}).nullable().optional()}),$o=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()})),ft=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:$o.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:ut,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 Bo=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()})}),Ao=zod.z.enum(["none","auto","required"]),Fo=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),zo=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()})})),be=zod.z.object({text:zod.z.string().min(1),type:zod.z.literal("text")}),Do=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()})}),Ko=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)})}),Ho=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(be).min(1))}),Go=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([be,Do])).min(1))}),Yo=zod.z.object({role:zod.z.literal("assistant"),content:zod.z.string().min(1).or(zod.z.array(be).min(1)).optional(),tool_calls:zod.z.array(Ko).min(1).optional()}),Vo=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),Jo=zod.z.union([Ho,Go,Yo,Vo]),gt=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(Jo).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_tokens:zod.z.number().min(0).nullable().optional(),presence_penalty:zod.z.number().min(-2).max(2).nullable().optional(),repetition_penalty:zod.z.number().min(0).max(2).nullable().optional(),response_format:zo.optional(),seed:zod.z.number().nullable().optional(),stop:zod.z.string().or(zod.z.array(zod.z.string()).max(4)).nullable().optional(),top_a:zod.z.number().min(0).max(1).nullable().optional(),temperature:zod.z.number().min(0).max(2).nullable().optional(),top_p:zod.z.number().min(0).max(1).nullable().optional(),top_k:zod.z.number().min(0).max(100).nullable().optional(),min_p:zod.z.number().min(0).max(1).nullable().optional(),tools:zod.z.array(Bo).optional(),tool_choice:Ao.or(Fo).optional()});var Wo=zod.z.object({apiKey:zod.z.string(),modelName:zod.z.string(),openRouterReferer:zod.z.string().optional(),openRouterTitle:zod.z.string().optional()}),z=class{constructor(t,n){this.version="v1";let a=Wo.parse(n);this.modelSchema=t,this.modelName=a.modelName,this.apiKey=a.apiKey,this.baseUrl=F(U.baseUrl),this.streamChatUrl=F(`${this.baseUrl}/chat/completions`),this.completeChatUrl=F(`${this.baseUrl}/chat/completions`),this.openRouterReferer=a.openRouterReferer,this.openRouterTitle=a.openRouterTitle;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return R(R({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",source:"adaline.ai"},this.openRouterReferer?{"HTTP-Referer":this.openRouterReferer}:{}),this.openRouterTitle?{"X-Title":this.openRouterTitle}:{})}getDefaultParams(){return {model:this.modelName}}getRetryDelay(t){return {shouldRetry:!0,delayMs:0}}getTokenCount(t){return t.reduce((n,a)=>n+a.content.map(r=>r.modality==="text"?r.value:"").join(" ").length,0)}transformModelRequest(t){let n=gt.safeParse(t);if(!n.success)throw new A({info:"Invalid model request",cause:n.error});let a=n.data,r=a.model;if(a.tool_choice&&(!a.tools||a.tools.length===0))throw new A({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let s={};a.response_format&&(s.responseFormat=a.response_format.type,a.response_format.type==="json_schema"&&(s.responseSchema={name:a.response_format.json_schema.name,description:a.response_format.json_schema.description||"",strict:a.response_format.json_schema.strict,schema:a.response_format.json_schema.schema})),a.tool_choice&&(typeof a.tool_choice=="string"?s.toolChoice=a.tool_choice:s.toolChoice=a.tool_choice.function.name),s.seed=a.seed,s.maxTokens=a.max_tokens,s.temperature=a.temperature,s.topA=a.top_a,s.topP=a.top_p,s.minP=a.min_p,s.topK=a.top_k,s.repetitionPenalty=a.repetition_penalty,s.presencePenalty=a.presence_penalty,s.frequencyPenalty=a.frequency_penalty,s.stop=a.stop,s.logProbs=a.logprobs,s.topLogProbs=a.top_logprobs;let d=ke().parse(st(s)),p=[],c={};a.messages.forEach(u=>{let y=u.role;switch(y){case"system":{let g=u.content;if(typeof g=="string")p.push({role:y,content:[{modality:T,value:g}]});else {let b=g.map(C=>({modality:T,value:C.text}));p.push({role:y,content:b});}}break;case"user":{let g=u.content;if(typeof g=="string")p.push({role:y,content:[{modality:T,value:g}]});else {let b=g.map(C=>C.type==="text"?{modality:T,value:C.text}:C.image_url.url.startsWith("data:")?{modality:x,detail:C.image_url.detail||"auto",value:{type:Y,base64:C.image_url.url,media_type:rt(C.image_url.url)}}:{modality:x,detail:C.image_url.detail||"auto",value:{type:V,url:C.image_url.url}});p.push({role:y,content:b});}}break;case"assistant":{let g=[];if(!u.content&&!u.tool_calls)throw new A({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("one of'content' or 'tool_calls' must be provided")});if(u.content){let b=u.content;typeof b=="string"?g.push({modality:T,value:b}):b.forEach(C=>{g.push({modality:T,value:C.text});});}u.tool_calls&&u.tool_calls.forEach((C,yt)=>{let K={modality:E,id:C.id,index:yt,name:C.function.name,arguments:C.function.arguments};g.push(K),c[K.id]=K;}),p.push({role:y,content:g});}break;case"tool":{let g=u;p.push({role:y,content:[{modality:_,id:g.tool_call_id,index:c[g.tool_call_id].index,name:c[g.tool_call_id].name,data:g.content}]});}break}});let h=[];return a.tools&&a.tools.forEach(u=>{h.push({type:"function",definition:{schema:{name:u.function.name,description:u.function.description||"",strict:u.function.strict,parameters:u.function.parameters}}});}),{modelName:r,config:d,messages:p,tools:h.length>0?h:void 0}}transformConfig(t,n,a){let r=t.toolChoice;delete t.toolChoice;let s=this.modelSchema.config.schema.safeParse(t);if(!s.success)throw new j({info:`Invalid config for model : '${this.modelName}'`,cause:s.error});let d=s.data;r!==void 0&&(d.toolChoice=r),Object.keys(d).forEach(c=>{if(!(c in this.modelSchema.config.def))throw new j({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${c}',
7
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let p=Object.keys(d).reduce((c,h)=>{let u=this.modelSchema.config.def[h],y=u.param,g=d[h];return y==="max_tokens"&&u.type==="range"&&g===0?c[y]=u.max:c[y]=g,c},{});if(p.top_logprobs&&!p.logprobs)throw new j({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'logprobs' must be 'true' when 'top_logprobs' is specified")});if("tool_choice"in p&&p.tool_choice!==void 0){let c=p.tool_choice;if(!a||a&&a.length===0)throw new j({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(a&&a.length>0){let h=this.modelSchema.config.def.toolChoice;if(!h.choices.includes(c))if(a.map(u=>u.definition.schema.name).includes(c))p.tool_choice={type:"function",function:{name:c}};else throw new j({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${c}' is not part of provided 'tools' names or
8
+ one of [${h.choices.join(", ")}]`)})}}if("response_format"in p&&p.response_format!==void 0){let c=p.response_format;if(c==="json_schema")if("response_schema"in p)p.response_format={type:"json_schema",json_schema:p.response_schema},delete p.response_schema;else throw new j({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});else p.response_format={type:c};}return p}transformMessages(t){if(!t||t&&t.length===0)return {messages:[]};let n=t.map(r=>{let s=L().safeParse(r);if(!s.success)throw new O({info:"Invalid messages",cause:s.error});return s.data});return n.forEach(r=>{r.content.forEach(s=>{if(!this.modelSchema.modalities.includes(s.modality))throw new O({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${s.modality}',
9
+ available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),n.forEach(r=>{if(!Object.keys(this.modelSchema.roles).includes(r.role))throw new O({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${r.role}',
10
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),{messages:n.map(r=>{switch(r.role){case I:{let s=[];return r.content.forEach(d=>{if(d.modality===T)s.push({type:"text",text:d.value});else throw new O({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${d.modality}'`)})}),{role:this.modelSchema.roles[r.role],content:s}}case v:{let s=[],d=[];return r.content.forEach(p=>{if(p.modality===T)s.push({type:"text",text:p.value});else if(p.modality===E)d.push({id:p.id,type:"function",function:{name:p.name,arguments:p.arguments}});else throw new O({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${p.modality}'`)})}),R({role:this.modelSchema.roles[r.role],content:s},d.length>0?{tool_calls:d}:{})}case k:{let s=[],d=[];r.content.forEach(c=>{if(c.modality===T)s.push({type:"text",text:c.value});else if(c.modality===x)d.push({type:"image_url",image_url:{url:c.value.type==="url"?c.value.url:c.value.base64,detail:c.detail}});else throw new O({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${c.modality}'`)})});let p=[...s,...d];return {role:this.modelSchema.roles[r.role],content:p}}case q:{if(r.content.length!==1)throw new O({info:`Invalid message for role : '${r.role}'`,cause:new Error(`role : '${r.role}' must have exactly one content item`)});if(r.content[0].modality!==_)throw new O({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' must have content with modality : '${_}'`)});let s=r.content[0];return {role:this.modelSchema.roles[r.role],tool_call_id:s.id,content:s.data}}default:throw new O({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' is not supported,
11
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(t){if(!this.modelSchema.modalities.includes(E))throw new ee({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${E}'`)});return !t||t&&t.length===0?{tools:[]}:{tools:t.map(r=>{let s=qe().safeParse(r);if(!s.success)throw new ee({info:"Invalid tools",cause:s.error});return s.data}).map(r=>({type:"function",function:r.definition.schema}))}}getCompleteChatUrl(t,n,a){return P(this,null,function*(){return new Promise(r=>{r(this.completeChatUrl);})})}getCompleteChatHeaders(t,n,a){return P(this,null,function*(){return new Promise(r=>{r(this.getDefaultHeaders());})})}getCompleteChatData(t,n,a){return P(this,null,function*(){let r=this.transformConfig(t,n,a),s=this.transformMessages(n);if(s.messages&&s.messages.length===0)throw new O({info:"Messages are required",cause:new Error("Messages are required")});let d=a?this.transformTools(a):{};return new Promise(p=>{p(R(R(R(R({},this.getDefaultParams()),r),s),d));})})}transformCompleteChatResponse(t){let n=ht.safeParse(t);if(n.success){if(n.data.choices.length===0)throw new N({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(n.data)}`)});let a=n.data,r=[],s=a.choices[0].message;s.content&&r.push(Q(v,s.content)),s.refusal&&r.push(Q(v,s.refusal)),s.tool_calls&&s.tool_calls.forEach((h,u)=>{r.push(je(v,u,h.id,h.function.name,h.function.arguments));});let d;a.usage&&(d={promptTokens:a.usage.prompt_tokens,completionTokens:a.usage.completion_tokens,totalTokens:a.usage.total_tokens});let p=[],c=a.choices[0].logprobs;return c&&(c.content&&p.push(...c.content.map(h=>({token:h.token,logProb:h.logprob,bytes:h.bytes,topLogProbs:h.top_logprobs.map(u=>({token:u.token,logProb:u.logprob,bytes:u.bytes}))}))),c.refusal&&p.push(...c.refusal.map(h=>({token:h.token,logProb:h.logprob,bytes:h.bytes,topLogProbs:h.top_logprobs.map(u=>({token:u.token,logProb:u.logprob,bytes:u.bytes}))})))),{messages:r,usage:d,logProbs:p}}throw new N({info:"Invalid response from model",cause:n.error})}getStreamChatUrl(t,n,a){return P(this,null,function*(){return new Promise(r=>{r(this.streamChatUrl);})})}getStreamChatHeaders(t,n,a){return P(this,null,function*(){return new Promise(r=>{r(this.getDefaultHeaders());})})}getStreamChatData(t,n,a){return P(this,null,function*(){let r=this.transformConfig(t,n,a),s=this.transformMessages(n);if(s.messages&&s.messages.length===0)throw new O({info:"Messages are required",cause:new Error("Messages are required")});let d=a?this.transformTools(a):{};return new Promise(p=>{p(R(R(R(R({stream:!0,stream_options:{include_usage:!0}},this.getDefaultParams()),r),s),d));})})}transformStreamChatResponseChunk(t,n){return Re(this,null,function*(){var r,s;let a=(n+t).split(`
12
+ `).filter(d=>d.trim()!=="");for(let d of a){if(d==="data: [DONE]")return;if(d.startsWith("data: {")&&d.endsWith("}")){let p;try{p=JSON.parse(d.substring(6));}catch(h){throw new N({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${p}`)})}let c=ft.safeParse(p);if(c.success){let h={partialMessages:[]},u=c.data;if(u.choices.length>0){let y=u.choices[0].delta;if(y!==void 0&&Object.keys(y).length!==0){if("content"in y&&y.content!==null)h.partialMessages.push(X(v,y.content));else if("refusal"in y&&y.refusal!==null)h.partialMessages.push(X(v,y.refusal));else if("tool_calls"in y&&y.tool_calls!==void 0){let g=y.tool_calls.at(0);h.partialMessages.push(Ie(v,g.index,g.id,(r=g.function)==null?void 0:r.name,(s=g.function)==null?void 0:s.arguments));}}}u.usage&&(h.usage={promptTokens:u.usage.prompt_tokens,completionTokens:u.usage.completion_tokens,totalTokens:u.usage.total_tokens}),yield {partialResponse:h,buffer:n};}else throw new N({info:"Invalid response from model",cause:c.error})}}})}};var ye=at(pt,dt).parse({name:"open-router-base-chat-model",description:"Base chat model for Open Router",maxInputTokens:128e3,maxOutputTokens:128e3,roles:mt,modalities:ct,config:{def:ge.base(128e3,4).def,schema:ge.base(128e3,4).schema}});
13
+
14
+ exports.BaseChatModel = z;
15
+ exports.BaseChatModelSchema = ye;
16
+ exports.ChatModelBaseConfigDef = lt;
17
+ exports.ChatModelBaseConfigSchema = it;
18
+ exports.OpenRouter = U;
19
+ exports.OpenRouterChatModelConfigs = ge;
20
+ exports.frequencyPenalty = me;
21
+ exports.logProbs = ue;
22
+ exports.maxTokens = ie;
23
+ exports.minP = Tn;
24
+ exports.presencePenalty = ce;
25
+ exports.repetitionPenalty = Rn;
26
+ exports.responseFormat = vn;
27
+ exports.seed = de;
28
+ exports.stop = le;
29
+ exports.temperature = re;
30
+ exports.toolChoice = fe;
31
+ exports.topA = bn;
32
+ exports.topK = Cn;
33
+ exports.topLogProbs = he;
34
+ exports.topP = pe;
35
+ //# sourceMappingURL=index.js.map
36
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/configs/chat-model/base.config.chat-model.open-router.ts","../../../../packages/types/src/errors/gateway-base.error.ts","../../../../packages/types/src/message/roles.ts","../../../../packages/types/src/message/content/image-content.ts","../../../../packages/types/src/message/content/text-content.ts","../../../../packages/types/src/message/content/tool-call-content.ts","../../../../packages/types/src/message/content/tool-response-content.ts","../../../../packages/types/src/message/content/content.ts","../../../../packages/types/src/message/message.ts","../../../../packages/types/src/utils/create-message.ts","../../../../packages/types/src/config/config.ts","../../../../packages/types/src/config/response-schema.config.ts","../../../../packages/types/src/tool/function-tool.ts","../../../../packages/types/src/tool/tool.ts","../../../../packages/types/src/embedding/embedding-requests.ts","../../../../packages/types/src/embedding/embedding-response.ts","../../../../packages/types/src/chat/chat-response.ts","../../../../packages/provider/src/errors/provider.error.ts","../../../../packages/provider/src/errors/model-response.error.ts","../../../../packages/provider/src/errors/invalid-model-request.error.ts","../../../../packages/provider/src/errors/invalid-config.error.ts","../../../../packages/provider/src/errors/invalid-messages.error.ts","../../../../packages/provider/src/errors/invalid-tools.error.ts","../../../../packages/provider/src/errors/invalid-embedding-requests.error.ts","../../../../packages/provider/src/types/config/multi-string-config-item.ts","../../../../packages/provider/src/types/config/range-config-item.ts","../../../../packages/provider/src/types/config/select-string-config-item.ts","../../../../packages/provider/src/types/config/object-schema-config-item.ts","../../../../packages/provider/src/types/config/select-boolean-config-item.ts","../../../../packages/provider/src/types/config/config-item.ts","../../../../packages/provider/src/model/chat-model/chat-model.schema.v1.ts","../../../../packages/provider/src/types/headers.ts","../../../../packages/provider/src/types/params.ts","../../../../packages/provider/src/types/url.ts","../../../../packages/provider/src/utils/common-config.def.chat-model.ts","../../../../packages/provider/src/utils/remove-undefined-entries.ts","../../../../packages/provider/src/utils/base64.ts","../../../../packages/provider/src/utils/url.ts","../src/configs/chat-model/common.config.chat-model.open-router.ts","../src/configs/configs.openai-router.ts","../src/provider/provider.open-router.ts","../src/models/chat-models/types/roles.chat-model.open-router.ts","../src/models/chat-models/types/modalities.chat-model.open-router.ts","../src/models/chat-models/types/response.chat-model.open-router.ts","../src/models/chat-models/types/request.chat-model.open-router.ts","../src/models/chat-models/base-chat-model.open-router.ts","../src/models/chat-models/base-chat-model-schema.open-router.ts"],"names":["safeStringify","obj","seen","key","value","getErrorMessage","error","GatewayBaseErrorLiteral","GatewayBaseError","_GatewayBaseError","info","cause","name","SystemRoleLiteral","UserRoleLiteral","AssistantRoleLiteral","ToolRoleLiteral","RoleLiterals","RoleEnum","z","PartialRoleLiterals","PartialRoleEnum","ImageModalityLiteral","Base64ImageContentTypeLiteral","Base64ImageContentMediaTypeLiterals","Base64ImageContentValue","UrlImageContentTypeLiteral","UrlImageContentValue","ImageContentValue","ImageContentDetails","ImageContentDetailsLiteral","ImageContent","Metadata","TextModalityLiteral","TextContent","PartialTextModalityLiteral","PartialTextContent","ToolCallModalityLiteral","ToolCallContent","PartialToolCallModalityLiteral","PartialToolCallContent","ToolResponseModalityLiteral","ToolResponseContent","ModalityLiterals","ModalityEnum","Content","TextContentMetadata","ImageContentMetadata","ToolCallContentMetadata","ToolResponseContentMetadata","PartialModalityLiterals","PartialModalityEnum","PartialContent","PartialTextContentMetadata","PartialToolCallContentMetadata","Message","Role","MessageMetadata","PartialMessage","createTextContent","createTextMessage","role","content","createToolCallMessage","index","id","args","createPartialTextMessage","createPartialToolCallMessage","Config","ResponseSchemaTypes","ResponseSchemaTypesLiteral","ResponseSchemaProperty","ResponseSchemaStructure","FunctionToolLiteral","FunctionParameterTypesLiteral","FunctionParameter","FunctionParameters","Function","ToolTypesLiteral","FunctionTool","ToolLiterals","ToolEnum","Tool","FunctionToolMetadata","EmbeddingTextModalityLiteral","EmbeddingTokenModalityLiteral","EmbeddingModalityLiterals","TokenEmbeddingRequests","FloatEmbeddingLiteral","FloatEmbedding","Base64EmbeddingLiteral","Base64Embedding","EmbeddingsUsage","ChatUsage","ChatBaseLogProb","ChatLogProb","ChatLogProbs","PartialChatResponse","ProviderErrorLiteral","ProviderError","_ProviderError","ModelResponseErrorLiteral","ModelResponseError","_ModelResponseError","InvalidModelRequestErrorLiteral","InvalidModelRequestError","_InvalidModelRequestError","InvalidConfigErrorLiteral","InvalidConfigError","_InvalidConfigError","InvalidMessagesErrorLiteral","InvalidMessagesError","_InvalidMessagesError","InvalidToolsErrorLiteral","InvalidToolsError","_InvalidToolsError","MultiStringConfigItemTypeLiteral","MultiStringConfigItemDef","MultiStringConfigItemSchema","max","MultiStringConfigItem","data","__spreadValues","RangeConfigItemTypeLiteral","RangeConfigItemDef","RangeConfigItemSchema","min","step","defaultValue","RangeConfigItem","SelectStringConfigItemTypeLiteral","SelectStringConfigItemDef","SelectStringConfigItemSchema","choices","SelectStringConfigItem","ObjectSchemaConfigItemTypeLiteral","ObjectSchemaConfigItemDef","SelectBooleanConfigItemTypeLiteral","SelectBooleanConfigItemDef","SelectBooleanConfigItemSchema","SelectBooleanConfigItem","ConfigItemLiterals","ConfigItemDef","ChatModelSchema","Roles","Modalities","config","_a","_b","defKeys","schemaKeys","Url","TEMPERATURE","MAX_TOKENS","STOP","TOP_A","TOP_P","TOP_K","MIN_P","FREQUENCY_PENALTY","PRESENCE_PENALTY","SEED","REPETITION_PENALTY","LOG_PROBS","TOP_LOG_PROBS","ECHO","RESPONSE_FORMAT","RESPONSE_FORMAT_WITH_SCHEMA","RESPONSE_SCHEMA","CHAT_CONFIG","removeUndefinedEntries","record","_","getMimeTypeFromBase64","base64","urlWithoutTrailingSlash","url","temperature","ot","Kt","maxTokens","maxOutputTokens","stop","maxSequences","Ve","topA","topK","topP","minP","frequencyPenalty","presencePenalty","repetitionPenalty","seed","logProbs","dt","topLogProbs","toolChoice","at","responseFormat","ChatModelBaseConfigSchema","ChatModelBaseConfigDef","OpenRouterChatModelConfigs","ProviderLiteral","OpenRouter","j","options","modelOptions","BaseChatModel","BaseChatModelSchema","OpenRouterChatModelRoles","oe","ae","ie","OpenRouterChatModelRolesMap","OpenRouterChatModelModalities","M","Z","g","h","OpenRouterChatModelModalitiesEnum","OpenRouterBaseLogProb","OpenRouterLogProb","OpenRouterToolCallsCompleteChatResponse","OpenRouterCompleteChatResponse","OpenRouterToolCallsStreamChatResponse","OpenRouterStreamChatResponse","OpenRouterChatRequestTool","OpenRouterChatRequestToolChoiceEnum","OpenRouterChatRequestToolChoiceFunction","OpenRouterChatRequestResponseFormat","OpenRouterChatRequestTextContent","OpenRouterChatRequestImageContent","OpenRouterChatRequestToolCallContent","OpenRouterChatRequestSystemMessage","OpenRouterChatRequestUserMessage","OpenRouterChatRequestAssistantMessage","OpenRouterChatRequestToolMessage","OpenRouterChatRequestMessage","OpenRouterChatRequest","BaseChatModelOptions","modelSchema","parsedOptions","an","responseHeaders","messages","acc","message","request","safeRequest","L","parsedRequest","modelName","_config","It","Qt","toolCallMap","_content","c","v","rn","B","assistantContent","toolCall","toolCallContent","toolResponse","tools","tool","_toolChoice","_parsedConfig","parsedConfig","transformedConfig","def","paramKey","paramValue","configToolChoice","parsedMessages","parsedMessage","b","q","textContent","toolCalls","imageContent","combinedContent","parsedTool","Gt","__async","resolve","transformedMessages","transformedTools","response","safe","parsedResponse","Tt","Ct","usage","_logProbs","logProb","topLogProb","chunk","buffer","__asyncGenerator","lines","line","structuredLine","partialResponse","ft","Mt","Rt"],"mappings":";;;;AAAA,IAAA,EAAA,CAAA,MAAA,CAAA,cAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,qBAAA,CAAA,IAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,cAAA,CAAA,EAAA,CAAA,MAAA,CAAA,SAAA,CAAA,oBAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CAAA,CAAA,CAAA,MAAA,CAAA,CAAA,CAAA,EAAA,CAAA,CAAA,MAAA,CAAA,GAAA,CAAA,SAAA,CAAA,CAAA,CAAA,CAAA,IAAA,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,GAAA,CA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CAAK,KAAQ,CAAA,CAAC,CAAE,CAAA,GAAA,CAChD,MAAQA,CAAAA,EAAAA,CAA2B,IAAK,CAAA,KAAA,CAAQ,CAAC,CAAA,CAAE,MACrD,CACF,CAAC","file":"index.js","sourcesContent":["import { z } from \"zod\";\n\nimport {\n frequencyPenalty,\n logProbs,\n maxTokens,\n presencePenalty,\n seed,\n stop,\n temperature,\n toolChoice,\n topLogProbs,\n topP,\n} from \"./common.config.chat-model.open-router\";\n\nconst ChatModelBaseConfigSchema = (maxOutputTokens: number, maxSequences: number) =>\n z.object({\n temperature: temperature.schema,\n maxTokens: maxTokens(maxOutputTokens).schema,\n stop: stop(maxSequences).schema,\n topP: topP.schema,\n frequencyPenalty: frequencyPenalty.schema,\n presencePenalty: presencePenalty.schema,\n seed: seed.schema.transform((value) => (value === 0 ? undefined : value)),\n logProbs: logProbs.schema,\n topLogProbs: topLogProbs.schema,\n toolChoice: toolChoice.schema,\n });\n\nconst ChatModelBaseConfigDef = (maxOutputTokens: number, maxSequences: number) =>\n ({\n temperature: temperature.def,\n maxTokens: maxTokens(maxOutputTokens).def,\n stop: stop(maxSequences).def,\n topP: topP.def,\n frequencyPenalty: frequencyPenalty.def,\n presencePenalty: presencePenalty.def,\n seed: seed.def,\n logProbs: logProbs.def,\n topLogProbs: topLogProbs.def,\n toolChoice: toolChoice.def,\n }) as const;\n\nexport { ChatModelBaseConfigDef, ChatModelBaseConfigSchema };\n","const safeStringify = (obj: unknown) => {\n const seen = new WeakSet();\n return JSON.stringify(obj, (key, value) => {\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n return; // Skip circular reference\n }\n seen.add(value);\n }\n return value;\n });\n}\n\nconst getErrorMessage = (error: unknown | undefined): string => {\n if (error == null) return \"unknown error\";\n if (typeof error === \"string\") return error;\n if (error instanceof Error) return error.message;\n return safeStringify(error);\n};\n\nconst GatewayBaseErrorLiteral = \"GatewayBaseError\" as const;\nclass GatewayBaseError extends Error {\n readonly name: string = GatewayBaseErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }, name?: string) {\n super(`[${name ?? GatewayBaseErrorLiteral}]: ${info}\\nMessage: ${getErrorMessage(cause)}`);\n this.info = info;\n this.cause = cause;\n this.name = name ?? GatewayBaseErrorLiteral;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static isGatewayBaseError(error: unknown): error is GatewayBaseError {\n return error instanceof GatewayBaseError;\n }\n\n toJSON(): object {\n return {\n name: this.name,\n info: this.info,\n cause: this.cause,\n message: this.message,\n stack: this.stack,\n };\n }\n}\n\nexport { GatewayBaseError };","import { z } from \"zod\";\n\nconst SystemRoleLiteral = \"system\" as const;\nconst UserRoleLiteral = \"user\" as const;\nconst AssistantRoleLiteral = \"assistant\" as const;\nconst ToolRoleLiteral = \"tool\" as const;\n\nconst RoleLiterals = [SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral] as const;\nconst RoleEnum = z.enum(RoleLiterals);\ntype RoleEnumType = z.infer<typeof RoleEnum>;\n\nconst PartialRoleLiterals = [AssistantRoleLiteral] as const;\nconst PartialRoleEnum = z.enum(PartialRoleLiterals);\ntype PartialRoleEnumType = z.infer<typeof PartialRoleEnum>;\n\nexport { \n UserRoleLiteral,\n ToolRoleLiteral, \n SystemRoleLiteral, \n AssistantRoleLiteral, \n RoleEnum, \n RoleLiterals, \n PartialRoleEnum, \n PartialRoleLiterals, \n type RoleEnumType,\n type PartialRoleEnumType, \n};\n","import { z } from \"zod\";\n\nconst ImageModalityLiteral = \"image\" as const;\n\nconst Base64ImageContentTypeLiteral = \"base64\" as const;\nconst Base64ImageContentMediaTypeLiterals = [\"png\", \"jpeg\", \"webp\", \"gif\"] as const;\nconst Base64ImageContentValue = z.object({\n type: z.literal(Base64ImageContentTypeLiteral),\n base64: z.string(),\n media_type: z.enum(Base64ImageContentMediaTypeLiterals),\n});\ntype Base64ImageContentValueType = z.infer<typeof Base64ImageContentValue>;\n\nconst UrlImageContentTypeLiteral = \"url\" as const;\nconst UrlImageContentValue = z.object({\n type: z.literal(UrlImageContentTypeLiteral),\n url: z.string(),\n});\ntype UrlImageContentValueType = z.infer<typeof UrlImageContentValue>;\n\nconst ImageContentValue = z.discriminatedUnion(\"type\", [Base64ImageContentValue, UrlImageContentValue]);\ntype ImageContentValueType = z.infer<typeof ImageContentValue>;\n\nconst ImageContentDetails = [\"low\", \"medium\", \"high\", \"auto\"] as const;\nconst ImageContentDetailsLiteral = z.enum(ImageContentDetails);\ntype ImageContentDetailsLiteralType = z.infer<typeof ImageContentDetailsLiteral>;\nconst ImageContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n z.object({\n modality: z.literal(ImageModalityLiteral),\n detail: ImageContentDetailsLiteral,\n value: ImageContentValue,\n metadata: Metadata,\n });\ntype ImageContentType<M extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof ImageContent<M>>>;\n\nexport {\n Base64ImageContentValue,\n ImageContent,\n ImageContentDetails,\n ImageContentDetailsLiteral,\n ImageModalityLiteral,\n UrlImageContentValue,\n UrlImageContentTypeLiteral,\n Base64ImageContentTypeLiteral,\n Base64ImageContentMediaTypeLiterals,\n type Base64ImageContentValueType,\n type ImageContentDetailsLiteralType,\n type ImageContentType,\n type ImageContentValueType,\n type UrlImageContentValueType,\n};\n","import { z } from \"zod\";\n\nconst TextModalityLiteral = \"text\" as const;\n\nconst TextContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n z.object({\n modality: z.literal(TextModalityLiteral),\n value: z.string(),\n metadata: Metadata,\n });\ntype TextContentType<M extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof TextContent<M>>>;\n\nconst PartialTextModalityLiteral = \"partial-text\" as const;\n\n// text value can already be an empty string, so we don't need to make it optional\n// const PartialTextContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n// TextContent(Metadata).merge(z.object({\n// modality: z.literal(PartialTextModalityLiteral),\n// }));\nconst PartialTextContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n z.object({\n modality: z.literal(PartialTextModalityLiteral),\n value: z.string(),\n metadata: Metadata,\n });\ntype PartialTextContentType<M extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof PartialTextContent<M>>>;\n\nexport { \n TextContent, \n PartialTextContent,\n TextModalityLiteral,\n PartialTextModalityLiteral,\n type TextContentType,\n type PartialTextContentType,\n};\n","import { z } from \"zod\";\n\nconst ToolCallModalityLiteral = \"tool-call\" as const;\n\nconst ToolCallContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n z.object({\n modality: z.literal(ToolCallModalityLiteral),\n index: z.number().int().nonnegative(),\n id: z.string().min(1),\n name: z.string().min(1),\n arguments: z.string(),\n metadata: Metadata,\n });\ntype ToolCallContentType<M extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof ToolCallContent<M>>>;\n\nconst PartialToolCallModalityLiteral = \"partial-tool-call\" as const;\n\n// const PartialToolCallContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n// ToolCallContent(Metadata).partial({\n// id: true,\n// name: true,\n// arguments: true,\n// }).merge(z.object({\n// modality: z.literal(PartialToolCallModalityLiteral),\n// }));\nconst PartialToolCallContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n z.object({\n modality: z.literal(PartialToolCallModalityLiteral),\n index: z.number().int().nonnegative(),\n id: z.string().optional(),\n name: z.string().optional(),\n arguments: z.string().optional(),\n metadata: Metadata,\n });\ntype PartialToolCallContentType<M extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof PartialToolCallContent<M>>>;\n\nexport { \n ToolCallContent, \n PartialToolCallContent,\n ToolCallModalityLiteral, \n PartialToolCallModalityLiteral,\n type ToolCallContentType, \n type PartialToolCallContentType \n};\n","import { z } from \"zod\";\n\nconst ToolResponseModalityLiteral = \"tool-response\" as const;\n\nconst ToolResponseContent = <M extends z.ZodTypeAny = z.ZodUndefined>(Metadata: M = z.undefined() as M) =>\n z.object({\n modality: z.literal(ToolResponseModalityLiteral),\n index: z.number().int().nonnegative(),\n id: z.string().min(1),\n name: z.string().min(1),\n data: z.string(),\n metadata: Metadata,\n });\ntype ToolResponseContentType<M extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof ToolResponseContent<M>>>;\n\nexport { ToolResponseContent, ToolResponseModalityLiteral, type ToolResponseContentType };\n","import { z } from \"zod\";\n\nimport { ImageContent, ImageModalityLiteral } from \"./image-content\";\nimport { TextContent, TextModalityLiteral, PartialTextContent, PartialTextModalityLiteral } from \"./text-content\";\nimport { ToolCallContent, ToolCallModalityLiteral, PartialToolCallContent, PartialToolCallModalityLiteral } from \"./tool-call-content\";\nimport { ToolResponseContent, ToolResponseModalityLiteral } from \"./tool-response-content\";\n\nconst ModalityLiterals = [TextModalityLiteral, ImageModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral] as const;\nconst ModalityEnum = z.enum(ModalityLiterals);\ntype ModalityEnumType = z.infer<typeof ModalityEnum>;\n\nconst Content = <\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n ICM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n RCM extends z.ZodTypeAny = z.ZodUndefined,\n>(\n TextContentMetadata: TCM = z.undefined() as TCM,\n ImageContentMetadata: ICM = z.undefined() as ICM,\n ToolCallContentMetadata: CCM = z.undefined() as CCM,\n ToolResponseContentMetadata: RCM = z.undefined() as RCM\n) =>\n z.discriminatedUnion(\"modality\", [\n TextContent(TextContentMetadata),\n ImageContent(ImageContentMetadata),\n ToolCallContent(ToolCallContentMetadata),\n ToolResponseContent(ToolResponseContentMetadata),\n ]);\ntype ContentType<\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n ICM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n RCM extends z.ZodTypeAny = z.ZodUndefined,\n> = z.infer<ReturnType<typeof Content<TCM, ICM, CCM, RCM>>>;\n\nconst PartialModalityLiterals = [PartialTextModalityLiteral, PartialToolCallModalityLiteral] as const;\nconst PartialModalityEnum = z.enum(PartialModalityLiterals);\ntype PartialModalityEnumType = z.infer<typeof PartialModalityEnum>;\n\nconst PartialContent = <\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n>(\n PartialTextContentMetadata: TCM = z.undefined() as TCM,\n PartialToolCallContentMetadata: CCM = z.undefined() as CCM,\n) => \n z.discriminatedUnion(\"modality\", [\n PartialTextContent(PartialTextContentMetadata),\n PartialToolCallContent(PartialToolCallContentMetadata),\n ]);\ntype PartialContentType<\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n> = z.infer<ReturnType<typeof PartialContent<TCM, CCM>>>;\n\n\nexport { \n Content, \n ModalityEnum, \n ModalityLiterals, \n type ContentType, \n type ModalityEnumType,\n PartialContent,\n PartialModalityEnum,\n PartialModalityLiterals,\n type PartialContentType,\n type PartialModalityEnumType,\n};\n","import { z } from \"zod\";\n\nimport { Content, PartialContent } from \"./content\";\nimport { RoleEnum, PartialRoleEnum } from \"./roles\";\n\nconst Message = <\n R extends z.ZodEnum<[string, ...string[]]> = typeof RoleEnum,\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n ICM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n RCM extends z.ZodTypeAny = z.ZodUndefined,\n MM extends z.ZodTypeAny = z.ZodUndefined,\n>(\n Role: R = RoleEnum as unknown as R,\n TextContentMetadata: TCM = z.undefined() as TCM,\n ImageContentMetadata: ICM = z.undefined() as ICM,\n ToolCallContentMetadata: CCM = z.undefined() as CCM,\n ToolResponseContentMetadata: RCM = z.undefined() as RCM,\n MessageMetadata: MM = z.undefined() as MM\n) =>\n z.object({\n role: Role,\n content: z.array(Content(TextContentMetadata, ImageContentMetadata, ToolCallContentMetadata, ToolResponseContentMetadata)),\n metadata: MessageMetadata,\n });\ntype MessageType<\n R extends z.ZodEnum<[string, ...string[]]> = typeof RoleEnum,\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n ICM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n RCM extends z.ZodTypeAny = z.ZodUndefined,\n MM extends z.ZodTypeAny = z.ZodUndefined,\n> = z.infer<ReturnType<typeof Message<R, TCM, ICM, CCM, RCM, MM>>>;\n\n// const PartialMessage = <\n// R extends z.ZodEnum<[string, ...string[]]> = typeof PartialRoleEnum,\n// TCM extends z.ZodTypeAny = z.ZodUndefined,\n// CCM extends z.ZodTypeAny = z.ZodUndefined,\n// MM extends z.ZodTypeAny = z.ZodUndefined,\n// >(\n// Role: R = PartialRoleEnum as unknown as R,\n// TextContentMetadata: TCM = z.undefined() as TCM,\n// ToolCallContentMetadata: CCM = z.undefined() as CCM,\n// MessageMetadata: MM = z.undefined() as MM,\n// ) => Message(\n// Role, \n// TextContentMetadata, \n// undefined, \n// ToolCallContentMetadata, \n// undefined, \n// MessageMetadata\n// ).omit({ content: true }).merge(z.object({\n// partialContent: PartialContent(TextContentMetadata, ToolCallContentMetadata),\n// }));\nconst PartialMessage = <\n R extends z.ZodEnum<[string, ...string[]]> = typeof PartialRoleEnum,\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n MM extends z.ZodTypeAny = z.ZodUndefined,\n>(\n Role: R = PartialRoleEnum as unknown as R,\n TextContentMetadata: TCM = z.undefined() as TCM,\n ToolCallContentMetadata: CCM = z.undefined() as CCM,\n MessageMetadata: MM = z.undefined() as MM,\n) => z.object({\n role: Role,\n partialContent: PartialContent(TextContentMetadata, ToolCallContentMetadata),\n metadata: MessageMetadata,\n});\ntype PartialMessageType<\n R extends z.ZodEnum<[string, ...string[]]> = typeof PartialRoleEnum,\n TCM extends z.ZodTypeAny = z.ZodUndefined,\n CCM extends z.ZodTypeAny = z.ZodUndefined,\n MM extends z.ZodTypeAny = z.ZodUndefined,\n> = z.infer<ReturnType<typeof PartialMessage<R, TCM, CCM, MM>>>;\n\nexport { \n Message, \n PartialMessage,\n type MessageType,\n type PartialMessageType,\n};\n","import { \n RoleEnumType,\n TextContent,\n TextModalityLiteral,\n ImageContent,\n ImageModalityLiteral,\n ImageContentDetailsLiteralType,\n UrlImageContentTypeLiteral,\n Base64ImageContentTypeLiteral,\n ToolCallContent,\n ToolCallModalityLiteral,\n ToolResponseContent,\n ToolResponseModalityLiteral,\n Message,\n MessageType,\n ContentType,\n PartialTextContent,\n PartialTextModalityLiteral,\n PartialToolCallContent,\n PartialToolCallModalityLiteral,\n PartialMessage,\n PartialMessageType,\n} from \"./../message\";\n\nconst createTextContent = (content: string): ContentType => {\n return TextContent().parse({\n modality: TextModalityLiteral,\n value: content\n });\n};\n\nconst createToolCallContent = (index: number, id: string, name: string, args: string): ContentType => {\n return ToolCallContent().parse({\n modality: ToolCallModalityLiteral,\n index: index,\n id: id,\n name: name,\n arguments: args\n });\n};\n\nconst createTextMessage = (role: RoleEnumType, content: string): MessageType => {\n return Message().parse({\n role: role,\n content: [TextContent().parse({\n modality: TextModalityLiteral,\n value: content\n })]\n });\n};\n\n const createUrlImageMessage = (role: RoleEnumType, url: string, detail: ImageContentDetailsLiteralType): MessageType => {\n return Message().parse({\n role: role,\n content: [ImageContent().parse({\n modality: ImageModalityLiteral,\n detail: detail,\n value: {\n type: UrlImageContentTypeLiteral,\n url: url\n }\n })]\n });\n};\n\nconst createBase64ImageMessage = (role: RoleEnumType, base64: string, detail: ImageContentDetailsLiteralType): MessageType => {\n return Message().parse({\n role: role,\n content: [ImageContent().parse({\n modality: ImageModalityLiteral,\n detail: detail,\n value: {\n type: Base64ImageContentTypeLiteral,\n base64: base64\n }\n })]\n });\n};\n\nconst createToolCallMessage = (role: RoleEnumType, index: number, id: string, name: string, args: string): MessageType => {\n return Message().parse({\n role: role,\n content: [ToolCallContent().parse({\n modality: ToolCallModalityLiteral,\n index: index,\n id: id,\n name: name,\n arguments: args\n })]\n });\n};\n\nconst createToolResponseMessage = (role: RoleEnumType, index: number, id: string, name: string, data: string): MessageType => {\n return Message().parse({\n role: role,\n content: [ToolResponseContent().parse({\n modality: ToolResponseModalityLiteral,\n index: index,\n id: id,\n name: name,\n data: data\n })]\n });\n};\n\nconst createPartialTextMessage = (role: RoleEnumType, content: string): PartialMessageType => {\n return PartialMessage().parse({\n role: role,\n partialContent: PartialTextContent().parse({\n modality: PartialTextModalityLiteral,\n value: content\n })\n });\n};\n\nconst createPartialToolCallMessage = (role: RoleEnumType, index: number, id?: string, name?: string, args?: string): PartialMessageType => {\n return PartialMessage().parse({\n role: role,\n partialContent: PartialToolCallContent().parse({\n modality: PartialToolCallModalityLiteral,\n index: index,\n id: id,\n name: name,\n arguments: args\n })\n });\n};\n\nexport {\n createTextContent,\n createTextMessage,\n createUrlImageMessage,\n createBase64ImageMessage,\n createToolCallContent,\n createToolCallMessage,\n createToolResponseMessage,\n createPartialTextMessage,\n createPartialToolCallMessage,\n};","import { z } from \"zod\";\n\n// TODO: rename to MessageConfig or something, has to be relevant for language model only\nconst Config = <\nC extends z.ZodRecord<z.ZodString, z.ZodAny> = z.ZodRecord<z.ZodString, z.ZodAny>\n>(\n Config: C = z.record(z.string(), z.any()).optional() as unknown as C\n) => Config;\ntype ConfigType<\n C extends z.ZodRecord<z.ZodString, z.ZodAny> = z.ZodRecord<z.ZodString, z.ZodAny>\n> = z.infer<ReturnType<typeof Config<C>>>;\n\nexport { \n Config, \n type ConfigType \n};","import { z } from \"zod\";\n\n// TODO: move to json schema 7 type and validator when implemented for tool types\nconst ResponseSchemaTypes = [\"object\", \"array\", \"number\", \"string\", \"boolean\", \"enum\"] as const;\nconst ResponseSchemaTypesLiteral = z.enum(ResponseSchemaTypes);\ntype ResponseSchemaTypesType = z.infer<typeof ResponseSchemaTypesLiteral>;\n\nconst ResponseSchemaProperty = z.object({\n anyOf: z.array(z.any()).optional(),\n type: z.union([ResponseSchemaTypesLiteral, z.array(z.union([ResponseSchemaTypesLiteral, z.literal(\"null\")]))]).optional(),\n default: z.any().optional(),\n title: z.string().optional(),\n description: z.string().max(4096).optional(),\n properties: z.record(z.any()).optional(),\n required: z.array(z.string()).optional(),\n minItems: z.number().int().min(0).optional(),\n maxItems: z.number().int().optional(),\n items: z.record(z.any()).optional(), // Recursive structure to handle nested arrays and objects\n enum: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(), // Enum for allowed values\n minimum: z.number().optional(), // Minimum value for number\n maximum: z.number().optional(), // Maximum value for number\n minLength: z.number().int().min(0).optional(), // Minimum length for string\n maxLength: z.number().int().optional(), // Maximum length for string\n $ref: z.string().optional(), // Reference to another schema\n});\ntype ResponseSchemaPropertyType = z.infer<typeof ResponseSchemaProperty>;\n\nconst ResponseSchemaStructure = z.object({\n type: z.enum([\"object\"]),\n required: z.array(z.string()),\n $defs: z.record(z.any()).optional(),\n properties: z.record(ResponseSchemaProperty),\n additionalProperties: z.literal(false),\n});\ntype ResponseSchemaStructureType = z.infer<typeof ResponseSchemaStructure>;\n\nconst ResponseSchema = z\n .object({\n name: z\n .string()\n .regex(/^[a-zA-Z0-9_]{1,64}$/)\n .max(64),\n description: z.string().max(4096),\n strict: z.boolean().optional(),\n schema: ResponseSchemaStructure,\n })\n .optional();\ntype ResponseSchemaType = z.infer<typeof ResponseSchema>;\n\nexport { \n ResponseSchema, \n ResponseSchemaProperty, \n ResponseSchemaStructure, \n ResponseSchemaTypes,\n ResponseSchemaTypesLiteral,\n type ResponseSchemaTypesType,\n type ResponseSchemaType,\n type ResponseSchemaPropertyType,\n type ResponseSchemaStructureType,\n};\n","// import { JSONSchema7 } from \"json-schema\";\n// import { Validator } from \"jsonschema\";\nimport { z } from \"zod\";\n\nconst FunctionToolLiteral = \"function\" as const;\n\n// // TODO: fix 'name' property not allowed in JSONSchema7\n// const FunctionTool = z.object({\n// type: z.literal(FunctionToolLiteral),\n// definition: z.object({\n// schema: z.object({}).refine((schema) => {\n// const validator = new Validator();\n// return validator.validate(schema, { type: \"object\" }).valid;\n// }),\n// }),\n// callback: z.function().args(z.string().min(0)).returns(z.promise(z.any())).optional(),\n// });\n\n// const FunctionTool = z.object({\n// type: z.literal(FunctionToolLiteral),\n// definition: z.object({\n// schema: z.object({}),\n// }),\n// callback: z.function().args(z.string().min(0)).returns(z.promise(z.any())).optional(),\n// });\n// type FunctionToolType = z.infer<typeof FunctionTool>;\n\nconst FunctionParameterTypes = [\"object\", \"array\", \"number\", \"string\", \"boolean\", \"null\"];\nconst FunctionParameterTypesLiteral = z.enum([\"object\", \"array\", \"number\", \"string\", \"boolean\", \"null\"]);\ntype FunctionParameterTypesType = z.infer<typeof FunctionParameterTypesLiteral>;\n\n// TODO: make a proper fix here\nconst FunctionParameter = z.object({\n anyOf: z.array(z.any()).optional(),\n type: FunctionParameterTypesLiteral.optional(),\n default: z.any().optional(),\n title: z.string().optional(),\n description: z.string().max(4096).optional(),\n properties: z.record(z.any()).optional(),\n required: z.array(z.string()).optional(),\n minItems: z.number().int().min(0).optional(),\n maxItems: z.number().int().optional(),\n items: z.record(z.any()).optional(), // Recursive structure to handle nested arrays and objects\n enum: z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional(), // Enum for allowed values\n minimum: z.number().optional(), // Minimum value for number\n maximum: z.number().optional(), // Maximum value for number\n minLength: z.number().int().min(0).optional(), // Minimum length for string\n maxLength: z.number().int().optional(), // Maximum length for string\n});\ntype FunctionParameterType = z.infer<typeof FunctionParameter>;\n\nconst FunctionParameters = z.object({\n type: z.enum([\"object\"]),\n title: z.string().optional(),\n $defs: z.record(z.any()).optional(),\n properties: z.record(FunctionParameter).optional(),\n required: z.array(z.string()).optional(),\n});\ntype FunctionParametersType = z.infer<typeof FunctionParameters>;\n\nconst Function = z.object({\n name: z\n .string()\n .regex(/^[a-zA-Z0-9_]{1,64}$/)\n .max(64),\n description: z.string().max(4096),\n parameters: z.any(),\n strict: z.boolean().optional(),\n});\ntype FunctionType = z.infer<typeof Function>;\n\nconst ToolTypes = [\"function\"];\nconst ToolTypesLiteral = z.enum([\"function\"]);\ntype ToolTypesType = z.infer<typeof ToolTypesLiteral>;\n\nconst FunctionTool = z.object({\n type: ToolTypesLiteral,\n definition: z.object({\n schema: Function, // TODO: convert to union with more tool types\n }),\n});\ntype FunctionToolType = z.infer<typeof FunctionTool>;\n\n// const Tools = z.array(Tool).nonempty().optional();\n// type ToolsType = z.infer<typeof Tools>;\n\nexport {\n Function,\n FunctionParameter,\n FunctionParameters,\n FunctionParameterTypes,\n FunctionParameterTypesLiteral,\n ToolTypes,\n ToolTypesLiteral,\n type FunctionParametersType,\n type FunctionParameterType,\n type FunctionParameterTypesType,\n type FunctionType,\n type ToolTypesType,\n};\n\nexport { FunctionTool, FunctionToolLiteral, type FunctionToolType };\n","import { z } from \"zod\";\n\nimport { FunctionTool, FunctionToolLiteral } from \"./function-tool\";\n\nconst ToolLiterals = [FunctionToolLiteral] as const;\nconst ToolEnum = z.enum(ToolLiterals);\ntype ToolEnumType = z.infer<typeof ToolEnum>;\n\nconst Tool = <FTM extends z.ZodTypeAny>(FunctionToolMetadata: FTM = z.undefined() as FTM) =>\n z.discriminatedUnion(\"type\", [FunctionTool.extend({ metadata: FunctionToolMetadata })]);\ntype ToolType<FTM extends z.ZodTypeAny = z.ZodUndefined> = z.infer<ReturnType<typeof Tool<FTM>>>;\n\nexport { Tool, ToolEnum, ToolLiterals, type ToolEnumType, type ToolType };\n","import { z } from \"zod\";\n\nconst EmbeddingTextModalityLiteral = \"text\" as const;\nconst EmbeddingTokenModalityLiteral = \"token\" as const;\n\nconst EmbeddingModalityLiterals = [EmbeddingTextModalityLiteral, EmbeddingTokenModalityLiteral] as const;\nconst EmbeddingModalityEnum = z.enum(EmbeddingModalityLiterals);\ntype EmbeddingModalityEnumType = z.infer<typeof EmbeddingModalityEnum>;\n\nconst TextEmbeddingRequests = z.array(z.string().min(1));\ntype TextEmbeddingRequestsType = z.infer<typeof TextEmbeddingRequests>;\n\nconst TokenEmbeddingRequests = z.array(z.array(z.number().int().nonnegative())); //TODO: check if zero or negative values are allowed\ntype TokenEmbeddingRequestsType = z.infer<typeof TokenEmbeddingRequests>;\n\nconst EmbeddingRequests = <\nM extends z.ZodTypeAny = z.ZodUndefined\n>(\n Metadata: M = z.undefined() as M\n) => z.discriminatedUnion(\"modality\", [\n z.object({\n modality: z.literal(EmbeddingTextModalityLiteral),\n metadata: Metadata,\n requests: TextEmbeddingRequests,\n }),\n z.object({\n modality: z.literal(EmbeddingTokenModalityLiteral),\n metadata: Metadata,\n requests: TokenEmbeddingRequests,\n }),\n]);\ntype EmbeddingRequestsType<\n M extends z.ZodTypeAny = z.ZodUndefined,\n> = z.infer<ReturnType<typeof EmbeddingRequests<M>>>;\n\nexport {\n EmbeddingTextModalityLiteral,\n EmbeddingTokenModalityLiteral,\n EmbeddingModalityLiterals,\n EmbeddingModalityEnum,\n TextEmbeddingRequests,\n TokenEmbeddingRequests,\n EmbeddingRequests,\n type EmbeddingRequestsType,\n type EmbeddingModalityEnumType,\n type TextEmbeddingRequestsType,\n type TokenEmbeddingRequestsType,\n};","import { z } from \"zod\";\n\nconst FloatEmbeddingLiteral = \"float\" as const;\nconst FloatEmbedding = z.object({\n index: z.number().int().nonnegative(),\n embedding: z.array(z.number()),\n});\ntype FloatEmbeddingType = z.infer<typeof FloatEmbedding>;\n\nconst Base64EmbeddingLiteral = \"base64\" as const;\nconst Base64Embedding = z.object({\n index: z.number().int().nonnegative(),\n embedding: z.string().base64(),\n});\ntype Base64EmbeddingType = z.infer<typeof Base64Embedding>;\n\nconst EmbeddingsUsage = z.object({\n totalTokens: z.number().int().nonnegative(),\n});\ntype EmbeddingsUsageType = z.infer<typeof EmbeddingsUsage>;\n\nconst EmbeddingResponse = z.discriminatedUnion(\"encodingFormat\", [\n z.object({\n encodingFormat: z.literal(FloatEmbeddingLiteral),\n embeddings: z.array(FloatEmbedding),\n usage: EmbeddingsUsage.optional(),\n }),\n z.object({\n encodingFormat: z.literal(Base64EmbeddingLiteral),\n embeddings: z.array(Base64Embedding),\n usage: EmbeddingsUsage.optional(),\n }),\n]);\ntype EmbeddingResponseType = z.infer<typeof EmbeddingResponse>;\n\nexport {\n FloatEmbeddingLiteral,\n Base64EmbeddingLiteral,\n FloatEmbedding,\n Base64Embedding,\n EmbeddingsUsage,\n EmbeddingResponse,\n type FloatEmbeddingType,\n type Base64EmbeddingType,\n type EmbeddingsUsageType,\n type EmbeddingResponseType,\n};","import { z } from \"zod\";\n\nimport { Message, PartialMessage } from \"./../message\";\n\nconst ChatUsage = z.object({\n promptTokens: z.number().nonnegative(),\n completionTokens: z.number().nonnegative(),\n totalTokens: z.number().nonnegative(),\n});\ntype ChatUsageType = z.infer<typeof ChatUsage>;\n\nconst ChatBaseLogProb = z.object({\n token: z.string(),\n logProb: z.number(),\n bytes: z.array(z.number().int()).nullable(),\n});\ntype ChatBaseLogProbType = z.infer<typeof ChatBaseLogProb>;\n\nconst ChatLogProb = ChatBaseLogProb.extend({\n topLogProbs: z.array(ChatBaseLogProb),\n});\ntype ChatLogProbType = z.infer<typeof ChatLogProb>;\n\nconst ChatLogProbs = z.array(ChatLogProb);\ntype ChatLogProbsType = z.infer<typeof ChatLogProbs>;\n\nconst ChatResponse = z.object({\n messages: z.array(Message()),\n usage: ChatUsage.optional(), // TODO: Make this required after all providers have implemented it\n logProbs: ChatLogProbs.optional(),\n});\ntype ChatResponseType = z.infer<typeof ChatResponse>;\n\nconst PartialChatResponse = z.object({\n partialMessages: z.array(PartialMessage()),\n usage: ChatUsage.optional(), // TODO: Make this required after all providers have implemented it\n logProbs: ChatLogProbs.optional(),\n});\ntype PartialChatResponseType = z.infer<typeof PartialChatResponse>;\n\nexport { \n ChatUsage, \n ChatBaseLogProb, \n ChatLogProb, \n ChatLogProbs, \n ChatResponse,\n PartialChatResponse,\n type ChatUsageType, \n type ChatBaseLogProbType, \n type ChatLogProbType, \n type ChatLogProbsType, \n type ChatResponseType,\n type PartialChatResponseType\n};\n","import { GatewayBaseError } from \"@adaline/types\";\n\nconst ProviderErrorLiteral = \"ProviderError\" as const;\nexport class ProviderError extends GatewayBaseError {\n readonly name = ProviderErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, ProviderErrorLiteral);\n this.info = info;\n this.cause = cause;\n }\n\n static isProviderError(error: unknown): error is ProviderError {\n return error instanceof ProviderError;\n }\n}","import { GatewayBaseError } from \"@adaline/types\";\n\nconst ModelResponseErrorLiteral = \"ModelResponseError\" as const;\nexport class ModelResponseError extends GatewayBaseError {\n readonly name = ModelResponseErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, ModelResponseErrorLiteral);\n this.cause = cause;\n this.info = info;\n }\n\n static isModelResponseError(error: unknown): error is ModelResponseError {\n return error instanceof ModelResponseError;\n }\n}\n","import { GatewayBaseError } from \"@adaline/types\";\n\nconst InvalidModelRequestErrorLiteral = \"InvalidModelRequestError\" as const;\nexport class InvalidModelRequestError extends GatewayBaseError {\n readonly name = InvalidModelRequestErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, InvalidModelRequestErrorLiteral);\n this.cause = cause;\n this.info = info;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static isInvalidModelRequestError(error: unknown): error is InvalidModelRequestError {\n return error instanceof InvalidModelRequestError;\n }\n}\n","import { GatewayBaseError } from \"@adaline/types\";\n\nconst InvalidConfigErrorLiteral = \"InvalidConfigError\" as const;\nexport class InvalidConfigError extends GatewayBaseError {\n readonly name = InvalidConfigErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, InvalidConfigErrorLiteral);\n this.cause = cause;\n this.info = info;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static isInvalidConfigError(error: unknown): error is InvalidConfigError {\n return error instanceof InvalidConfigError;\n }\n}\n","import { GatewayBaseError } from \"@adaline/types\";\n\nconst InvalidMessagesErrorLiteral = \"InvalidMessagesError\" as const;\nexport class InvalidMessagesError extends GatewayBaseError {\n readonly name = InvalidMessagesErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, InvalidMessagesErrorLiteral);\n this.cause = cause;\n this.info = info;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static isInvalidMessagesError(error: unknown): error is InvalidMessagesError {\n return error instanceof InvalidMessagesError;\n }\n}\n","import { GatewayBaseError } from \"@adaline/types\";\n\nconst InvalidToolsErrorLiteral = \"InvalidToolsError\" as const;\nexport class InvalidToolsError extends GatewayBaseError {\n readonly name = InvalidToolsErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, InvalidToolsErrorLiteral);\n this.cause = cause;\n this.info = info;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static isInvalidToolsError(error: unknown): error is InvalidToolsError {\n return error instanceof InvalidToolsError;\n }\n}\n","import { GatewayBaseError } from \"@adaline/types\";\n\nconst InvalidEmbeddingRequestsErrorLiteral = \"InvalidEmbeddingRequestsError\" as const;\nexport class InvalidEmbeddingRequestsError extends GatewayBaseError {\n readonly name = InvalidEmbeddingRequestsErrorLiteral;\n readonly info: string;\n readonly cause: unknown;\n\n constructor({ info, cause }: { info: string; cause: unknown }) {\n super({ info, cause }, InvalidEmbeddingRequestsErrorLiteral);\n this.info = info;\n this.cause = cause;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static isInvalidEmbeddingRequestsError(error: unknown): error is InvalidEmbeddingRequestsError {\n return error instanceof InvalidEmbeddingRequestsError;\n }\n}","import { z } from \"zod\";\n\nconst MultiStringConfigItemTypeLiteral = \"multi-string\" as const;\n\nconst MultiStringConfigItemDef = z.object({\n type: z.literal(MultiStringConfigItemTypeLiteral),\n param: z.string().min(1),\n title: z.string().min(1),\n description: z.string().min(1).max(500),\n max: z.number().int().positive(),\n});\ntype MultiStringConfigItemType = z.infer<typeof MultiStringConfigItemDef>;\n\nconst MultiStringConfigItemSchema = (max: number) => z.array(z.string()).max(max).default([]).optional();\ntype MultiStringConfigItemSchemaType = z.infer<ReturnType<typeof MultiStringConfigItemSchema>>;\n\nconst MultiStringConfigItem = (data: Omit<MultiStringConfigItemType, \"type\">) => {\n return {\n def: MultiStringConfigItemDef.parse({\n type: MultiStringConfigItemTypeLiteral,\n ...data,\n }),\n schema: MultiStringConfigItemSchema(data.max),\n };\n};\n\nexport {\n MultiStringConfigItem,\n MultiStringConfigItemDef,\n MultiStringConfigItemSchema,\n MultiStringConfigItemTypeLiteral,\n type MultiStringConfigItemSchemaType,\n type MultiStringConfigItemType,\n};\n","import { z } from \"zod\";\n\nconst RangeConfigItemTypeLiteral = \"range\" as const;\n\nconst RangeConfigItemDef = z.object({\n type: z.literal(RangeConfigItemTypeLiteral),\n param: z.string().min(1),\n title: z.string().min(1),\n description: z.string().min(1).max(500),\n min: z.number().int(),\n max: z.number().int(),\n step: z.number().positive(),\n default: z.number(),\n});\ntype RangeConfigItemDefType = z.infer<typeof RangeConfigItemDef>;\n\nconst RangeConfigItemSchema = (min: number, max: number, step: number, defaultValue: number) =>\n z.number().min(min).max(max).step(step).default(defaultValue).optional();\ntype RangeConfigItemSchemaType = z.infer<ReturnType<typeof RangeConfigItemSchema>>;\n\nconst RangeConfigItem = (data: Omit<RangeConfigItemDefType, \"type\">) => {\n return {\n def: RangeConfigItemDef.parse({\n type: RangeConfigItemTypeLiteral,\n ...data,\n }),\n schema: RangeConfigItemSchema(data.min, data.max, data.step, data.default),\n };\n};\n\nexport {\n RangeConfigItem,\n RangeConfigItemDef,\n RangeConfigItemSchema,\n RangeConfigItemTypeLiteral,\n type RangeConfigItemDefType,\n type RangeConfigItemSchemaType,\n};\n","import { z } from \"zod\";\n\nconst SelectStringConfigItemTypeLiteral = \"select-string\" as const;\n\nconst SelectStringConfigItemDef = z.object({\n type: z.literal(SelectStringConfigItemTypeLiteral),\n param: z.string().min(1),\n title: z.string().min(1),\n description: z.string().min(1).max(500),\n default: z.string().min(1).nullable(),\n choices: z.array(z.string().min(1)),\n});\ntype SelectStringConfigItemDefType = z.infer<typeof SelectStringConfigItemDef>;\n\nconst SelectStringConfigItemSchema = (defaultValue: string | null, choices: string[]) =>\n z\n .enum(choices as [string, ...string[]])\n .nullable()\n .default(defaultValue)\n .optional();\ntype SelectStringConfigItemSchemaType = z.infer<ReturnType<typeof SelectStringConfigItemSchema>>;\n\nconst SelectStringConfigItem = (data: Omit<SelectStringConfigItemDefType, \"type\">) => {\n return {\n def: SelectStringConfigItemDef.parse({\n type: SelectStringConfigItemTypeLiteral,\n ...data,\n }),\n schema: SelectStringConfigItemSchema(data.default, data.choices),\n };\n};\n\nexport {\n SelectStringConfigItem,\n SelectStringConfigItemDef,\n SelectStringConfigItemSchema,\n SelectStringConfigItemTypeLiteral,\n type SelectStringConfigItemDefType,\n type SelectStringConfigItemSchemaType,\n};\n","import { z } from \"zod\";\n\nconst ObjectSchemaConfigItemTypeLiteral = \"object-schema\" as const;\n\nconst ObjectSchemaConfigItemDef = z.object({\n type: z.literal(ObjectSchemaConfigItemTypeLiteral),\n param: z.string().min(1),\n title: z.string().min(1),\n description: z.string().min(1).max(500),\n objectSchema: z.any(),\n});\ntype ObjectSchemaConfigItemType = z.infer<typeof ObjectSchemaConfigItemDef>;\n\nconst ObjectSchemaConfigItemSchema = <S extends z.ZodRawShape>(schema: z.ZodObject<S>) => schema.optional();\ntype ObjectSchemaConfigItemSchemaType<S extends z.ZodRawShape = z.ZodRawShape> = z.infer<ReturnType<typeof ObjectSchemaConfigItemSchema<S>>>;\n\nconst ObjectSchemaConfigItem = (data: Omit<ObjectSchemaConfigItemType, \"type\">) => {\n return {\n def: ObjectSchemaConfigItemDef.parse({\n type: ObjectSchemaConfigItemTypeLiteral,\n ...data,\n }),\n schema: ObjectSchemaConfigItemSchema(data.objectSchema),\n };\n};\n\nexport {\n ObjectSchemaConfigItem,\n ObjectSchemaConfigItemDef,\n ObjectSchemaConfigItemSchema,\n ObjectSchemaConfigItemTypeLiteral,\n type ObjectSchemaConfigItemType,\n type ObjectSchemaConfigItemSchemaType,\n};","import { z } from \"zod\";\n\nconst SelectBooleanConfigItemTypeLiteral = \"select-boolean\" as const;\n\nconst SelectBooleanConfigItemDef = z.object({\n type: z.literal(SelectBooleanConfigItemTypeLiteral),\n param: z.string().min(1),\n title: z.string().min(1),\n description: z.string().min(1).max(500),\n default: z.boolean().nullable(),\n});\ntype SelectBooleanConfigItemDefType = z.infer<typeof SelectBooleanConfigItemDef>;\n\nconst SelectBooleanConfigItemSchema = (defaultValue: boolean | null) =>\n z\n .boolean()\n .nullable()\n .default(defaultValue) \n .optional();\ntype SelectBooleanConfigItemSchemaType = z.infer<ReturnType<typeof SelectBooleanConfigItemSchema>>;\n\nconst SelectBooleanConfigItem = (data: Omit<SelectBooleanConfigItemDefType, \"type\">) => {\n return {\n def: SelectBooleanConfigItemDef.parse({\n type: SelectBooleanConfigItemTypeLiteral,\n ...data,\n }),\n schema: SelectBooleanConfigItemSchema(data.default),\n };\n};\n\nexport {\n SelectBooleanConfigItem,\n SelectBooleanConfigItemDef,\n SelectBooleanConfigItemSchema,\n SelectBooleanConfigItemTypeLiteral,\n type SelectBooleanConfigItemDefType,\n type SelectBooleanConfigItemSchemaType,\n};\n","import { z } from \"zod\";\n\nimport { MultiStringConfigItemDef, MultiStringConfigItemTypeLiteral } from \"./multi-string-config-item\";\nimport { RangeConfigItemDef, RangeConfigItemTypeLiteral } from \"./range-config-item\";\nimport { SelectStringConfigItemDef, SelectStringConfigItemTypeLiteral } from \"./select-string-config-item\";\nimport { ObjectSchemaConfigItemDef, ObjectSchemaConfigItemTypeLiteral } from \"./object-schema-config-item\";\nimport { SelectBooleanConfigItemDef, SelectBooleanConfigItemTypeLiteral } from \"./select-boolean-config-item\";\n\nconst ConfigItemLiterals = [\n RangeConfigItemTypeLiteral, \n MultiStringConfigItemTypeLiteral, \n SelectStringConfigItemTypeLiteral,\n ObjectSchemaConfigItemTypeLiteral,\n SelectBooleanConfigItemTypeLiteral,\n] as const;\nconst ConfigItemEnum = z.enum(ConfigItemLiterals);\ntype ConfigItemEnumType = z.infer<typeof ConfigItemEnum>;\n\nconst ConfigItemDef = z.discriminatedUnion(\"type\", [\n RangeConfigItemDef, \n MultiStringConfigItemDef, \n SelectStringConfigItemDef,\n SelectBooleanConfigItemDef,\n ObjectSchemaConfigItemDef,\n]);\ntype ConfigItemDefType = z.infer<typeof ConfigItemDef>;\n\nexport { ConfigItemDef, ConfigItemEnum, ConfigItemLiterals, type ConfigItemDefType, type ConfigItemEnumType };\n","import { z } from \"zod\";\n\nimport { ModalityEnum, RoleEnum } from \"@adaline/types\";\n\nimport { ConfigItemDef } from \"../../types/config\";\n\nconst ChatModelSchema = <\n R extends z.ZodEnum<[string, ...string[]]> = typeof RoleEnum,\n M extends z.ZodEnum<[string, ...string[]]> = typeof ModalityEnum\n>(\n Roles: R = RoleEnum as unknown as R, \n Modalities: M = ModalityEnum as unknown as M\n) =>\n z.object({\n name: z.string().min(1),\n description: z.string().min(1),\n roles: z.record(Roles, z.string().min(1).optional()),\n modalities: z.array(Modalities).nonempty(),\n maxInputTokens: z.number().int().positive().min(1),\n maxOutputTokens: z.number().int().positive().min(1),\n config: z\n .object({\n def: z.record(z.string().min(1), ConfigItemDef),\n schema: z.instanceof(z.ZodObject),\n })\n .refine(\n (config) => {\n const defKeys = Object.keys(config.def);\n const schemaKeys = Object.keys(config.schema?.shape ?? {});\n return defKeys.every((key) => schemaKeys.includes(key)) && schemaKeys.every((key) => defKeys.includes(key));\n },\n {\n message: \"Keys in 'config.def' must exactly match keys in 'config.schema'\",\n }\n ),\n });\ntype ChatModelSchemaType<\n R extends z.ZodEnum<[string, ...string[]]> = typeof RoleEnum,\n M extends z.ZodEnum<[string, ...string[]]> = typeof ModalityEnum\n> = z.infer<ReturnType<typeof ChatModelSchema<R, M>>>;\n\nexport { \n ChatModelSchema, \n type ChatModelSchemaType \n};\n","import { z } from \"zod\";\n\nconst Headers = z.record(z.string());\ntype HeadersType = z.infer<typeof Headers>;\n\nexport { Headers, type HeadersType };\n","import { z } from \"zod\";\n\nconst Params = z.record(z.union([\n z.boolean(),\n z.string(), \n z.number(), \n z.object({}),\n z.array(z.any()), // TODO: any or undefined?\n z.null(), \n z.undefined(), \n]));\ntype ParamsType = z.infer<typeof Params>;\n\nexport { Params, type ParamsType };\n","import { z } from \"zod\";\n\nconst Url = z.string().url();\ntype UrlType = z.infer<typeof Url>;\n\nexport { Url, type UrlType };\n","const TEMPERATURE = {\n type: \"range\",\n title: \"Temperature\",\n description:\n \"Adjusts the model's creativity level. With a setting of 0, the model strictly picks the most probable next word. \\\n For endeavors that benefit from a dash of inventiveness, consider dialing it up to 0.7 or higher, enabling the model to produce text \\\n that's unexpectedly fresh.\",\n} as const;\n\nconst MAX_TOKENS = {\n type: \"range\",\n title: \"Max tokens\",\n description:\n \"Specify the total tokens for generation, where one token approximates four English characters. \\\n Setting this to 0 defaults to the model's maximum capacity.\",\n} as const;\n\nconst STOP = (max: number) =>\n ({\n type: \"multi\",\n title: \"Stop sequence\",\n description: \n `Enter up to ${max} sequences that will halt additional text output. \\\n The generated text will exclude these sequences.`,\n }) as const;\n\nconst TOP_A = {\n type: \"range\",\n title: \"Top A\",\n description:\n \"Considers only the top tokens that have 'sufficiently high' probabilities relative to the most likely token, \\\n functioning like a dynamic Top-P. \\\n A lower Top-A value narrows down the token choices based on the highest probability token, \\\n while a higher Top-A value refines the filtering without necessarily impacting the creativity of the output.\",\n} as const;\n\nconst TOP_P = {\n type: \"range\",\n title: \"Top P\",\n description:\n \"Selects a subset of likely tokens for generation, restricting choices to the top-P fraction of possibilities, \\\n such as the top 10% when P=0.1. \\\n This approach can limit the variety of the output. By default, it's set to 1, indicating no restriction. \\\n It's advised to adjust this parameter or temperature to modulate output diversity, but not to modify both simultaneously.\",\n} as const;\n\nconst TOP_K = {\n type: \"range\",\n title: \"Top K\",\n description:\n \"Select only from the highest K probabilities for each following word, effectively eliminating the less likely 'long tail' options.\",\n} as const;\n\nconst MIN_P = {\n type: \"range\",\n title: \"Min P\",\n description:\n \"Specifies the minimum probability a token must have to be considered, in relation to the probability of the most likely token. \\\n (This value varies based on the confidence level of the top token.) \\\n For example, if Min-P is set to 0.1, only tokens with at least 1/10th the probability of the highest-ranked token will be considered.\",\n} as const;\n\nconst FREQUENCY_PENALTY = {\n type: \"range\",\n title: \"Frequency penalty\",\n description:\n \"Minimize redundancy.\\\n By assigning a penalty to frequently used tokens within the text, the likelihood of repeating identical phrases is reduced. \\\n The default setting for this penalty is zero.\",\n} as const;\n\nconst PRESENCE_PENALTY = {\n type: \"range\",\n title: \"Presence penalty\",\n description:\n \"Enhance the introduction of novel subjects by reducing the preference for tokens that have already appeared in the text, \\\n thus boosting the chances of exploring fresh topics. \\\n The standard setting for this is zero.\",\n} as const;\n\nconst SEED = {\n type: \"range\",\n title: \"Seed\",\n description:\n \"When seed is fixed to a specific value, the model makes a best effort to provide the same response for repeated requests. \\\n Deterministic output isn't guaranteed. \\\n Also, changing the model or parameter settings, such as the temperature, \\\n can cause variations in the response even when you use the same seed value. \\\n By default, a random seed value is used.\",\n} as const;\n\nconst REPETITION_PENALTY = {\n type: \"range\",\n title: \"Repetition penalty\",\n description:\n \"Reduces the likelihood of repeating tokens from the input. \\\n Increasing this value makes the model less prone to repetition, but setting it too high may lead to less coherent output, \\\n often resulting in run-on sentences missing smaller words. \\\n The token penalty is scaled according to the original token's probability.\",\n} as const;\n\nconst LOG_PROBS = {\n type: \"boolean\",\n title: \"Log probs\",\n description:\n \"Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned.\",\n} as const;\n\nconst TOP_LOG_PROBS = {\n type: \"range\",\n title: \"Top log probs\",\n description:\n \"The number of most likely tokens to return at each token position, each with an associated log probability. \\\n 'logprobs' must be set to true if this parameter is used.\",\n} as const;\n\nconst ECHO = {\n type: \"boolean\",\n title: \"Echo\",\n description:\n \"If true, the response will contain the prompt.\",\n} as const;\n\nconst RESPONSE_FORMAT = {\n type: \"select\",\n title: \"Response format\",\n description:\n \"Choose the response format of your model. For JSON, you must include the string 'JSON' in some form within your system / user prompt.\",\n} as const;\n\nconst RESPONSE_FORMAT_WITH_SCHEMA = {\n type: \"select\",\n title: \"Response format\",\n description:\n \"Choose the response format of your model. 'json_object' colloquially known as JSON mode, instructs the model to respond with a valid \\\n JSON (must include the term 'json' in prompt). 'json_schema' colloquially known as structured outputs, allows you to specify a strict \\\n response schema that the model will adhere to.\",\n} as const; \n\nconst RESPONSE_SCHEMA = {\n type: \"object\",\n title: \"Response schema\",\n description: \"When response format is set to 'json_schema', the model will return a JSON object of the specified schema.\",\n} as const;\n\nconst CHAT_CONFIG = {\n TEMPERATURE,\n MAX_TOKENS,\n STOP,\n TOP_A,\n TOP_P,\n TOP_K,\n MIN_P,\n FREQUENCY_PENALTY,\n PRESENCE_PENALTY,\n REPETITION_PENALTY,\n SEED,\n LOG_PROBS,\n TOP_LOG_PROBS,\n ECHO,\n RESPONSE_FORMAT,\n RESPONSE_FORMAT_WITH_SCHEMA,\n RESPONSE_SCHEMA,\n};\n\nexport { CHAT_CONFIG };\n","const removeUndefinedEntries = <T = unknown>(record: Record<string, T | undefined>): Record<string, T> => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return Object.fromEntries(Object.entries(record).filter(([_, value]) => value != null)) as Record<string, T>;\n};\n\nexport { removeUndefinedEntries };\n","import { isRunningInBrowser } from \"./is-running-in-browser\";\n\nconst convertBase64ToUint8Array = (base64String: string): Uint8Array => {\n const base64Url = base64String.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const latin1string = globalThis.atob(base64Url);\n return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0)!);\n};\n\nconst convertUint8ArrayToBase64 = (array: Uint8Array): string => {\n let latin1string = \"\";\n\n // Note: regular for loop to support older JavaScript versions that\n // do not support for..of on Uint8Array\n for (let i = 0; i < array.length; i++) {\n latin1string += String.fromCodePoint(array[i]);\n }\n\n return globalThis.btoa(latin1string);\n};\n\nconst encodedBase64ToString = (base64: string): string => {\n if (isRunningInBrowser()) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); }\n const decoder = new TextDecoder(\"utf-8\");\n return decoder.decode(bytes);\n } else {\n return Buffer.from(base64, \"base64\").toString(\"utf-8\");\n }\n}\n\nconst getMimeTypeFromBase64 = (base64: string): string => {\n const mimeTypePrefix = base64.split(\";\")[0];\n const mimeType = mimeTypePrefix.split(\"/\")[1];\n return mimeType;\n}\n\nexport { convertBase64ToUint8Array, convertUint8ArrayToBase64, encodedBase64ToString, getMimeTypeFromBase64 };\n","const urlWithoutTrailingSlash = (url: string): string => {\n return url?.replace(/\\/$/, \"\");\n};\n\nexport { urlWithoutTrailingSlash };\n","import { CHAT_CONFIG, MultiStringConfigItem, RangeConfigItem, SelectStringConfigItem, SelectBooleanConfigItem } from \"@adaline/provider\";\n\nconst temperature = RangeConfigItem({\n param: \"temperature\",\n title: CHAT_CONFIG.TEMPERATURE.title,\n description: CHAT_CONFIG.TEMPERATURE.description,\n min: 0,\n max: 2,\n step: 0.01,\n default: 1,\n});\n\nconst maxTokens = (maxOutputTokens: number) =>\n RangeConfigItem({\n param: \"max_tokens\",\n title: CHAT_CONFIG.MAX_TOKENS.title,\n description: CHAT_CONFIG.MAX_TOKENS.description,\n min: 0,\n max: maxOutputTokens,\n step: 1,\n default: 0,\n });\n\nconst stop = (maxSequences: number) =>\n MultiStringConfigItem({\n param: \"stop\",\n title: CHAT_CONFIG.STOP(maxSequences).title,\n description: CHAT_CONFIG.STOP(maxSequences).description,\n max: maxSequences,\n });\n\nconst topA = RangeConfigItem({\n param: \"top_a\",\n title: CHAT_CONFIG.TOP_A.title,\n description: CHAT_CONFIG.TOP_A.description,\n min: 0,\n max: 1,\n step: 0.01,\n default: 0,\n});\n\nconst topK = RangeConfigItem({\n param: \"top_k\",\n title: CHAT_CONFIG.TOP_K.title,\n description: CHAT_CONFIG.TOP_K.description,\n min: 0,\n max: 100,\n step: 1,\n default: 0,\n});\n\nconst topP = RangeConfigItem({\n param: \"top_p\",\n title: CHAT_CONFIG.TOP_P.title,\n description: CHAT_CONFIG.TOP_P.description,\n min: 0,\n max: 1,\n step: 0.01,\n default: 1,\n});\n\nconst minP = RangeConfigItem({\n param: \"min_p\",\n title: CHAT_CONFIG.MIN_P.title,\n description: CHAT_CONFIG.MIN_P.description,\n min: 0,\n max: 1,\n step: 0.01,\n default: 0,\n});\n\nconst frequencyPenalty = RangeConfigItem({\n param: \"frequency_penalty\",\n title: CHAT_CONFIG.FREQUENCY_PENALTY.title,\n description: CHAT_CONFIG.FREQUENCY_PENALTY.description,\n min: -2,\n max: 2,\n step: 0.01,\n default: 0,\n});\n\nconst presencePenalty = RangeConfigItem({\n param: \"presence_penalty\",\n title: CHAT_CONFIG.PRESENCE_PENALTY.title,\n description: CHAT_CONFIG.PRESENCE_PENALTY.description,\n min: -2,\n max: 2,\n step: 0.01,\n default: 0,\n});\n\nconst repetitionPenalty = RangeConfigItem({\n param: \"repetition_penalty\",\n title: CHAT_CONFIG.REPETITION_PENALTY.title,\n description: CHAT_CONFIG.REPETITION_PENALTY.description,\n min: 0,\n max: 2,\n step: 0.01,\n default: 0,\n});\n\nconst seed = RangeConfigItem({\n param: \"seed\",\n title: CHAT_CONFIG.SEED.title,\n description: CHAT_CONFIG.SEED.description,\n min: 0,\n max: 1000000,\n step: 1,\n default: 0,\n});\n\nconst logProbs = SelectBooleanConfigItem({\n param: \"logprobs\",\n title: CHAT_CONFIG.LOG_PROBS.title,\n description: CHAT_CONFIG.LOG_PROBS.description,\n default: false,\n});\n\nconst topLogProbs = RangeConfigItem({\n param: \"top_logprobs\",\n title: CHAT_CONFIG.TOP_LOG_PROBS.title,\n description: CHAT_CONFIG.TOP_LOG_PROBS.description,\n min: 0,\n max: 20,\n step: 1,\n default: 0,\n});\n\nconst toolChoice = SelectStringConfigItem({\n param: \"tool_choice\",\n title: \"Tool choice\",\n description:\n \"Controls which (if any) tool is called by the model. \\\n 'none' means the model will not call a function. \\\n 'auto' means the model can pick between generating a message or calling a tool.\",\n default: \"auto\",\n choices: [\"auto\", \"required\", \"none\"],\n});\n\nconst responseFormat = SelectStringConfigItem({\n param: \"response_format\",\n title: CHAT_CONFIG.RESPONSE_FORMAT.title,\n description: CHAT_CONFIG.RESPONSE_FORMAT.description,\n default: \"text\",\n choices: [\"text\", \"json_object\"],\n});\n\n\nexport {\n frequencyPenalty,\n logProbs,\n maxTokens,\n presencePenalty,\n repetitionPenalty,\n seed,\n stop,\n temperature,\n toolChoice,\n topLogProbs,\n topP,\n topA,\n topK,\n minP,\n responseFormat,\n};\n","import {\n ChatModelBaseConfigDef,\n ChatModelBaseConfigSchema,\n} from \"./chat-model\";\n\nconst OpenRouterChatModelConfigs = {\n base: (maxOutputTokens: number, maxSequences: number) => ({\n def: ChatModelBaseConfigDef(maxOutputTokens, maxSequences),\n schema: ChatModelBaseConfigSchema(maxOutputTokens, maxSequences),\n }),\n} as const;\n\nexport { OpenRouterChatModelConfigs };\n","import { ChatModelSchemaType, ChatModelV1, EmbeddingModelSchemaType, EmbeddingModelV1, ProviderError, ProviderV1 } from \"@adaline/provider\";\n\nimport { BaseChatModel, BaseChatModelOptionsType, BaseChatModelSchema } from \"../models/chat-models\";\n\nconst ProviderLiteral = \"open-router\";\nclass OpenRouter<O extends Record<string, any> = Record<string, any>> implements ProviderV1<O> {\n readonly version = \"v1\" as const;\n readonly name = ProviderLiteral;\n static readonly baseUrl = \"https://openrouter.ai/api/v1\";\n\n chatModelLiterals(): string[] {\n throw new ProviderError({\n info: \"Not implemented\",\n cause: new Error(\"Not implemented\"),\n });\n }\n\n chatModel(name: string, options: O): ChatModelV1 {\n const modelOptions = {\n modelName: name,\n ...options,\n };\n return new BaseChatModel(BaseChatModelSchema, modelOptions as unknown as BaseChatModelOptionsType);\n }\n\n chatModelSchema(name: string): ChatModelSchemaType {\n return BaseChatModelSchema;\n }\n\n chatModelSchemas(): Record<string, ChatModelSchemaType> {\n throw new ProviderError({\n info: \"Not implemented\",\n cause: new Error(\"Not implemented\"),\n });\n }\n\n embeddingModelLiterals(): string[] {\n throw new ProviderError({\n info: \"Open Router does not support embedding models\",\n cause: new Error(\"Open Router does not support embedding models\"),\n });\n }\n\n embeddingModel(name: string, options: O): EmbeddingModelV1 {\n throw new ProviderError({\n info: \"Open Router does not support embedding models\",\n cause: new Error(\"Open Router does not support embedding models\"),\n });\n }\n\n embeddingModelSchema(name: string): EmbeddingModelSchemaType {\n throw new ProviderError({\n info: \"Open Router does not support embedding models\",\n cause: new Error(\"Open Router does not support embedding models\"),\n });\n }\n\n embeddingModelSchemas(): Record<string, EmbeddingModelSchemaType> {\n throw new ProviderError({\n info: \"Open Router does not support embedding models\",\n cause: new Error(\"Open Router does not support embedding models\"),\n });\n }\n}\n\nexport { OpenRouter };\n","import { z } from \"zod\";\n\nimport { AssistantRoleLiteral, SystemRoleLiteral, ToolRoleLiteral, UserRoleLiteral } from \"@adaline/types\";\n\nconst OpenRouterChatModelRoles = z.enum([SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral]);\n\nconst OpenRouterChatModelRolesMap = {\n system: SystemRoleLiteral,\n user: UserRoleLiteral,\n assistant: AssistantRoleLiteral,\n tool: ToolRoleLiteral,\n} as const;\n\nexport { \n OpenRouterChatModelRoles, \n OpenRouterChatModelRolesMap,\n};\n","import { z } from \"zod\";\n\nimport { ChatModelSchemaType } from \"@adaline/provider\";\nimport { ImageModalityLiteral, TextModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral } from \"@adaline/types\";\n\nconst OpenRouterChatModelModalities: ChatModelSchemaType[\"modalities\"] = [\n TextModalityLiteral,\n ImageModalityLiteral,\n ToolCallModalityLiteral,\n ToolResponseModalityLiteral,\n];\n\nconst OpenRouterChatModelModalitiesEnum = z.enum([\n TextModalityLiteral,\n ImageModalityLiteral,\n ToolCallModalityLiteral,\n ToolResponseModalityLiteral,\n]);\n\nexport {\n OpenRouterChatModelModalitiesEnum,\n OpenRouterChatModelModalities, \n};\n","import { z } from \"zod\";\n\nconst OpenRouterBaseLogProb = z.object({\n token: z.string(),\n logprob: z.number(),\n bytes: z.array(z.number()).nullable(),\n});\n\nconst OpenRouterLogProb = z.object({\n content: z.array(OpenRouterBaseLogProb.extend({\n top_logprobs: z.array(OpenRouterBaseLogProb),\n })).nullable(),\n refusal: z.array(OpenRouterBaseLogProb.extend({\n top_logprobs: z.array(OpenRouterBaseLogProb),\n })).nullable(),\n}).nullable();\n\nconst OpenRouterToolCallsCompleteChatResponse = z.array(\n z.object({\n id: z.string().min(1),\n type: z.enum([\"function\"]),\n function: z.object({\n name: z.string(),\n arguments: z.string(),\n }),\n })\n);\n\nconst OpenRouterCompleteChatResponse = z.object({\n id: z.string(),\n object: z.literal(\"chat.completion\"),\n created: z.number(),\n model: z.string(),\n system_fingerprint: z.string().nullable().optional(),\n choices: z.array(\n z.object({\n index: z.number(),\n message: z.object({\n role: z.string(),\n content: z.string().nullable().optional(),\n tool_calls: OpenRouterToolCallsCompleteChatResponse.optional(),\n refusal: z.string().nullable().optional(),\n }),\n logprobs: OpenRouterLogProb.optional(),\n finish_reason: z.string(),\n })\n ),\n usage: z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number(),\n }).nullable().optional(),\n});\ntype OpenRouterCompleteChatResponseType = z.infer<typeof OpenRouterCompleteChatResponse>;\n\nconst OpenRouterToolCallsStreamChatResponse = z.array(\n z.object({\n index: z.number().int(),\n id: z.string().min(1).optional(),\n type: z.enum([\"function\"]).optional(),\n function: z\n .object({\n name: z.string().min(1).optional(),\n arguments: z.string().optional(),\n })\n .optional(),\n })\n);\n\nconst OpenRouterStreamChatResponse = z.object({\n id: z.string(),\n object: z.string(),\n created: z.number(),\n model: z.string(),\n system_fingerprint: z.string().nullable().optional(),\n choices: z.array(\n z.object({\n index: z.number(),\n delta: z\n .object({\n content: z.string().nullable().optional(),\n tool_calls: OpenRouterToolCallsStreamChatResponse.optional(),\n refusal: z.string().nullable().optional(),\n })\n .or(z.object({})),\n logprobs: OpenRouterLogProb,\n finish_reason: z.string().nullable(),\n })\n ),\n usage: z.object({\n prompt_tokens: z.number(),\n completion_tokens: z.number(),\n total_tokens: z.number(),\n }).nullable().optional(),\n});\ntype OpenRouterStreamChatResponseType = z.infer<typeof OpenRouterStreamChatResponse>;\n\nexport {\n OpenRouterStreamChatResponse,\n OpenRouterCompleteChatResponse,\n OpenRouterToolCallsStreamChatResponse,\n OpenRouterToolCallsCompleteChatResponse,\n type OpenRouterStreamChatResponseType,\n type OpenRouterCompleteChatResponseType,\n}","import { z } from \"zod\";\n\nconst OpenRouterChatRequestTool = z.object({\n type: z.literal(\"function\"),\n function: z.object({\n name: z.string().min(1),\n description: z.string().min(1).optional(),\n strict: z.boolean().optional(),\n parameters: z.any(), // TODO: should be more strict\n }),\n});\ntype OpenRouterChatRequestToolType = z.infer<typeof OpenRouterChatRequestTool>;\n\nconst OpenRouterChatRequestToolChoiceEnum = z.enum([\"none\", \"auto\", \"required\"]);\ntype OpenRouterChatRequestToolChoiceEnumType = z.infer<typeof OpenRouterChatRequestToolChoiceEnum>;\n\nconst OpenRouterChatRequestToolChoiceFunction = z.object({\n type: z.literal(\"function\"),\n function: z.object({\n name: z.string().min(1),\n }),\n});\ntype OpenRouterChatRequestToolChoiceFunctionType = z.infer<typeof OpenRouterChatRequestToolChoiceFunction>;\n\nconst OpenRouterChatRequestResponseFormat = z\n .object({\n type: z.enum([\"text\", \"json_object\"]),\n })\n .or(\n z.object({\n type: z.literal(\"json_schema\"),\n json_schema: z.object({\n name: z.string().min(1),\n description: z.string().min(1).optional(),\n strict: z.boolean().optional(),\n schema: z.any(), // TODO: should be more strict\n }),\n })\n );\ntype OpenRouterChatRequestResponseFormatType = z.infer<typeof OpenRouterChatRequestResponseFormat>;\n\nconst OpenRouterChatRequestTextContent = z.object({\n text: z.string().min(1),\n type: z.literal(\"text\"),\n});\ntype OpenRouterChatRequestTextContentType = z.infer<typeof OpenRouterChatRequestTextContent>;\n\nconst OpenRouterChatRequestImageContent = z.object({\n type: z.literal(\"image_url\"),\n image_url: z.object({\n url: z.string().url().min(1),\n detail: z.enum([\"low\", \"high\", \"auto\"]).optional(),\n }),\n});\ntype OpenRouterChatRequestImageContentType = z.infer<typeof OpenRouterChatRequestImageContent>;\n\nconst OpenRouterChatRequestToolCallContent = z.object({\n id: z.string().min(1),\n type: z.literal(\"function\"),\n function: z.object({\n name: z.string().min(1),\n arguments: z.string().min(1),\n }),\n});\ntype OpenRouterChatRequestToolCallContentType = z.infer<typeof OpenRouterChatRequestToolCallContent>;\n\nconst OpenRouterChatRequestSystemMessage = z.object({\n role: z.literal(\"system\"),\n content: z.string().min(1).or(z.array(OpenRouterChatRequestTextContent).min(1)),\n});\ntype OpenRouterChatRequestSystemMessageType = z.infer<typeof OpenRouterChatRequestSystemMessage>;\n\nconst OpenRouterChatRequestUserMessage = z.object({\n role: z.literal(\"user\"),\n content: z\n .string().min(1)\n .or(z.array(z.union([OpenRouterChatRequestTextContent, OpenRouterChatRequestImageContent])).min(1)),\n});\ntype OpenRouterChatRequestUserMessageType = z.infer<typeof OpenRouterChatRequestUserMessage>;\n\nconst OpenRouterChatRequestAssistantMessage = z\n .object({\n role: z.literal(\"assistant\"),\n content: z.string().min(1).or(z.array(OpenRouterChatRequestTextContent).min(1)).optional(),\n tool_calls: z.array(OpenRouterChatRequestToolCallContent).min(1).optional(),\n })\ntype OpenRouterChatRequestAssistantMessageType = z.infer<typeof OpenRouterChatRequestAssistantMessage>;\n\nconst OpenRouterChatRequestToolMessage = z.object({\n role: z.literal(\"tool\"),\n tool_call_id: z.string().min(1),\n content: z.string().min(1),\n});\ntype OpenRouterChatRequestToolMessageType = z.infer<typeof OpenRouterChatRequestToolMessage>;\n\nconst OpenRouterChatRequestMessage = z.union([\n OpenRouterChatRequestSystemMessage,\n OpenRouterChatRequestUserMessage,\n OpenRouterChatRequestAssistantMessage,\n OpenRouterChatRequestToolMessage,\n]);\ntype OpenRouterChatRequestMessageType = z.infer<typeof OpenRouterChatRequestMessage>;\n\nconst OpenRouterChatRequest = z.object({\n model: z.string().min(1).optional(),\n messages: z.array(OpenRouterChatRequestMessage).min(1),\n frequency_penalty: z.number().min(-2).max(2).nullable().optional(),\n logprobs: z.boolean().nullable().optional(),\n top_logprobs: z.number().min(0).max(20).nullable().optional(),\n max_tokens: z.number().min(0).nullable().optional(),\n presence_penalty: z.number().min(-2).max(2).nullable().optional(),\n repetition_penalty: z.number().min(0).max(2).nullable().optional(),\n response_format: OpenRouterChatRequestResponseFormat.optional(),\n seed: z.number().nullable().optional(),\n stop: z.string().or(z.array(z.string()).max(4)).nullable().optional(),\n top_a: z.number().min(0).max(1).nullable().optional(),\n temperature: z.number().min(0).max(2).nullable().optional(),\n top_p: z.number().min(0).max(1).nullable().optional(),\n top_k: z.number().min(0).max(100).nullable().optional(),\n min_p: z.number().min(0).max(1).nullable().optional(),\n tools: z.array(OpenRouterChatRequestTool).optional(),\n tool_choice: OpenRouterChatRequestToolChoiceEnum.or(OpenRouterChatRequestToolChoiceFunction).optional(),\n});\ntype OpenRouterChatRequestType = z.infer<typeof OpenRouterChatRequest>;\n\nexport {\n OpenRouterChatRequest,\n OpenRouterChatRequestMessage,\n OpenRouterChatRequestSystemMessage,\n OpenRouterChatRequestUserMessage,\n OpenRouterChatRequestAssistantMessage,\n OpenRouterChatRequestToolMessage,\n OpenRouterChatRequestTextContent,\n OpenRouterChatRequestImageContent,\n OpenRouterChatRequestToolCallContent,\n OpenRouterChatRequestTool,\n OpenRouterChatRequestToolChoiceEnum,\n OpenRouterChatRequestToolChoiceFunction,\n OpenRouterChatRequestResponseFormat,\n type OpenRouterChatRequestType,\n type OpenRouterChatRequestMessageType,\n type OpenRouterChatRequestSystemMessageType,\n type OpenRouterChatRequestUserMessageType,\n type OpenRouterChatRequestAssistantMessageType,\n type OpenRouterChatRequestToolMessageType,\n type OpenRouterChatRequestTextContentType,\n type OpenRouterChatRequestImageContentType,\n type OpenRouterChatRequestToolCallContentType,\n type OpenRouterChatRequestToolType,\n type OpenRouterChatRequestToolChoiceEnumType,\n type OpenRouterChatRequestToolChoiceFunctionType,\n type OpenRouterChatRequestResponseFormatType,\n};\n","import { z } from \"zod\";\n\nimport {\n ChatModelSchemaType,\n ChatModelV1,\n getMimeTypeFromBase64,\n HeadersType,\n InvalidConfigError,\n InvalidMessagesError,\n InvalidModelRequestError,\n InvalidToolsError,\n ModelResponseError,\n ParamsType,\n removeUndefinedEntries,\n SelectStringConfigItemDefType,\n UrlType,\n urlWithoutTrailingSlash,\n} from \"@adaline/provider\";\nimport {\n AssistantRoleLiteral,\n Base64ImageContentTypeLiteral,\n Base64ImageContentValueType,\n ChatLogProbsType,\n ChatResponseType,\n ChatUsageType,\n Config,\n ConfigType,\n ContentType,\n createPartialTextMessage,\n createPartialToolCallMessage,\n createTextMessage,\n createToolCallMessage,\n ImageModalityLiteral,\n Message,\n MessageType,\n PartialChatResponseType,\n SystemRoleLiteral,\n TextModalityLiteral,\n Tool,\n ToolCallContentType,\n ToolCallModalityLiteral,\n ToolResponseContentType,\n ToolResponseModalityLiteral,\n ToolRoleLiteral,\n ToolType,\n UrlImageContentTypeLiteral,\n UserRoleLiteral,\n} from \"@adaline/types\";\n\nimport { OpenRouter } from \"../../provider/provider.open-router\";\nimport {\n OpenRouterChatRequest,\n OpenRouterChatRequestImageContentType,\n OpenRouterChatRequestTextContentType,\n OpenRouterChatRequestToolType,\n OpenRouterChatRequestType,\n OpenRouterCompleteChatResponse,\n OpenRouterCompleteChatResponseType,\n OpenRouterStreamChatResponse,\n OpenRouterStreamChatResponseType,\n} from \"./types\";\n\nconst BaseChatModelOptions = z.object({\n apiKey: z.string(),\n modelName: z.string(),\n openRouterReferer: z.string().optional(),\n openRouterTitle: z.string().optional(),\n});\ntype BaseChatModelOptionsType = z.infer<typeof BaseChatModelOptions>;\n\nclass BaseChatModel implements ChatModelV1<ChatModelSchemaType> {\n readonly version = \"v1\" as const;\n modelSchema: ChatModelSchemaType;\n\n private readonly modelName: string;\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly streamChatUrl: string;\n private readonly completeChatUrl: string;\n private readonly openRouterReferer: string | undefined;\n private readonly openRouterTitle: string | undefined;\n\n constructor(modelSchema: ChatModelSchemaType, options: BaseChatModelOptionsType) {\n const parsedOptions = BaseChatModelOptions.parse(options);\n this.modelSchema = modelSchema;\n this.modelName = parsedOptions.modelName;\n this.apiKey = parsedOptions.apiKey;\n this.baseUrl = urlWithoutTrailingSlash(OpenRouter.baseUrl);\n this.streamChatUrl = urlWithoutTrailingSlash(`${this.baseUrl}/chat/completions`);\n this.completeChatUrl = urlWithoutTrailingSlash(`${this.baseUrl}/chat/completions`);\n this.openRouterReferer = parsedOptions.openRouterReferer;\n this.openRouterTitle = parsedOptions.openRouterTitle;\n }\n\n getDefaultBaseUrl(): UrlType {\n return this.baseUrl;\n }\n\n getDefaultHeaders(): HeadersType {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n source: \"adaline.ai\",\n ...(this.openRouterReferer ? { \"HTTP-Referer\": this.openRouterReferer } : {}),\n ...(this.openRouterTitle ? { \"X-Title\": this.openRouterTitle } : {}),\n };\n }\n\n getDefaultParams(): ParamsType {\n return {\n model: this.modelName,\n };\n }\n\n getRetryDelay(responseHeaders: HeadersType): { shouldRetry: boolean; delayMs: number } {\n return { shouldRetry: true, delayMs: 0 };\n }\n\n // TODO: add support for non-text modalities\n // TODO: add support for tools if tools are counted as tokens\n // TODO: should validate messages and tools before counting tokens?\n getTokenCount(messages: MessageType[]): number {\n return messages.reduce((acc, message) => {\n return acc + message.content.map((content) => (content.modality === \"text\" ? content.value : \"\")).join(\" \").length;\n }, 0);\n }\n\n transformModelRequest(request: OpenRouterChatRequestType): {\n modelName: string | undefined;\n config: ConfigType;\n messages: MessageType[];\n tools: ToolType[] | undefined;\n } {\n const safeRequest = OpenRouterChatRequest.safeParse(request);\n if (!safeRequest.success) {\n throw new InvalidModelRequestError({ info: \"Invalid model request\", cause: safeRequest.error });\n }\n\n const parsedRequest = safeRequest.data;\n\n const modelName = parsedRequest.model;\n\n if (parsedRequest.tool_choice && (!parsedRequest.tools || parsedRequest.tools.length === 0)) {\n throw new InvalidModelRequestError({\n info: `Invalid model request for model : '${this.modelName}'`,\n cause: new Error(\"'tools' are required when 'tool_choice' is specified\"),\n });\n }\n\n const _config: ConfigType = {};\n if (parsedRequest.response_format) {\n _config.responseFormat = parsedRequest.response_format.type;\n if (parsedRequest.response_format.type === \"json_schema\") {\n _config.responseSchema = {\n name: parsedRequest.response_format.json_schema.name,\n description: parsedRequest.response_format.json_schema.description || \"\",\n strict: parsedRequest.response_format.json_schema.strict,\n schema: parsedRequest.response_format.json_schema.schema,\n };\n }\n }\n\n if (parsedRequest.tool_choice) {\n if (typeof parsedRequest.tool_choice === \"string\") {\n _config.toolChoice = parsedRequest.tool_choice;\n } else {\n _config.toolChoice = parsedRequest.tool_choice.function.name;\n }\n }\n\n _config.seed = parsedRequest.seed;\n _config.maxTokens = parsedRequest.max_tokens;\n _config.temperature = parsedRequest.temperature;\n _config.topA = parsedRequest.top_a;\n _config.topP = parsedRequest.top_p;\n _config.minP = parsedRequest.min_p;\n _config.topK = parsedRequest.top_k;\n _config.repetitionPenalty = parsedRequest.repetition_penalty;\n _config.presencePenalty = parsedRequest.presence_penalty;\n _config.frequencyPenalty = parsedRequest.frequency_penalty;\n _config.stop = parsedRequest.stop;\n _config.logProbs = parsedRequest.logprobs;\n _config.topLogProbs = parsedRequest.top_logprobs;\n\n const config = Config().parse(removeUndefinedEntries(_config));\n\n const messages: MessageType[] = [];\n const toolCallMap: { [id: string]: ToolCallContentType } = {};\n parsedRequest.messages.forEach((message) => {\n const role = message.role;\n switch (role) {\n case \"system\":\n {\n const content = message.content as string | OpenRouterChatRequestTextContentType[];\n if (typeof content === \"string\") {\n messages.push({\n role: role,\n content: [{ modality: TextModalityLiteral, value: content }],\n });\n } else {\n const _content = content.map((c) => {\n return { modality: TextModalityLiteral, value: c.text };\n });\n messages.push({ role: role, content: _content });\n }\n }\n break;\n\n case \"user\":\n {\n const content = message.content as string | (OpenRouterChatRequestTextContentType | OpenRouterChatRequestImageContentType)[];\n if (typeof content === \"string\") {\n messages.push({\n role: role,\n content: [{ modality: TextModalityLiteral, value: content }],\n });\n } else {\n const _content = content.map((c) => {\n if (c.type === \"text\") {\n return { modality: TextModalityLiteral, value: c.text };\n } else {\n if (c.image_url.url.startsWith(\"data:\")) {\n return {\n modality: ImageModalityLiteral,\n detail: c.image_url.detail || \"auto\",\n value: {\n type: Base64ImageContentTypeLiteral,\n base64: c.image_url.url,\n media_type: getMimeTypeFromBase64(c.image_url.url) as Base64ImageContentValueType[\"media_type\"],\n },\n };\n } else {\n return {\n modality: ImageModalityLiteral,\n detail: c.image_url.detail || \"auto\",\n value: { type: UrlImageContentTypeLiteral, url: c.image_url.url },\n };\n }\n }\n });\n messages.push({ role: role, content: _content });\n }\n }\n break;\n\n case \"assistant\":\n {\n const assistantContent: ContentType[] = [];\n\n if (!message.content && !message.tool_calls) {\n throw new InvalidModelRequestError({\n info: `Invalid model request for model : '${this.modelName}'`,\n cause: new Error(\"one of'content' or 'tool_calls' must be provided\"),\n });\n }\n\n if (message.content) {\n const content = message.content as string | OpenRouterChatRequestTextContentType[];\n if (typeof content === \"string\") {\n assistantContent.push({ modality: TextModalityLiteral, value: content });\n } else {\n content.forEach((c) => {\n assistantContent.push({ modality: TextModalityLiteral, value: c.text });\n });\n }\n }\n\n if (message.tool_calls) {\n const toolCalls = message.tool_calls;\n toolCalls.forEach((toolCall, index) => {\n const toolCallContent: ToolCallContentType = {\n modality: ToolCallModalityLiteral,\n id: toolCall.id,\n index: index,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n };\n assistantContent.push(toolCallContent);\n toolCallMap[toolCallContent.id] = toolCallContent;\n });\n }\n messages.push({ role: role, content: assistantContent });\n }\n break;\n\n case \"tool\":\n {\n const toolResponse = message;\n messages.push({\n role: role,\n content: [\n {\n modality: ToolResponseModalityLiteral,\n id: toolResponse.tool_call_id,\n index: toolCallMap[toolResponse.tool_call_id].index,\n name: toolCallMap[toolResponse.tool_call_id].name,\n data: toolResponse.content,\n },\n ],\n });\n }\n break;\n }\n });\n\n const tools: ToolType[] = [];\n if (parsedRequest.tools) {\n parsedRequest.tools.forEach((tool: OpenRouterChatRequestToolType) => {\n tools.push({\n type: \"function\",\n definition: {\n schema: {\n name: tool.function.name,\n description: tool.function.description || \"\",\n strict: tool.function.strict,\n parameters: tool.function.parameters,\n },\n },\n });\n });\n }\n\n return {\n modelName,\n config,\n messages,\n tools: tools.length > 0 ? tools : undefined,\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n transformConfig(config: ConfigType, messages?: MessageType[], tools?: ToolType[]): ParamsType {\n const _toolChoice = config.toolChoice;\n delete config.toolChoice; // can have a specific tool name that is not in the model schema, validated at transformation\n\n // TODO: why is safeParse coercing Record to modelSchema.config.schema type rather than returning error?\n const _parsedConfig = this.modelSchema.config.schema.safeParse(config);\n if (!_parsedConfig.success) {\n throw new InvalidConfigError({\n info: `Invalid config for model : '${this.modelName}'`,\n cause: _parsedConfig.error,\n });\n }\n\n const parsedConfig = _parsedConfig.data as ConfigType;\n if (_toolChoice !== undefined) {\n parsedConfig.toolChoice = _toolChoice;\n }\n\n Object.keys(parsedConfig).forEach((key) => {\n if (!(key in this.modelSchema.config.def)) {\n throw new InvalidConfigError({\n info: `Invalid config for model : '${this.modelName}'`,\n cause: new Error(`Invalid config key : '${key}', \n available keys : [${Object.keys(this.modelSchema.config.def).join(\", \")}]`),\n });\n }\n });\n\n const transformedConfig = Object.keys(parsedConfig).reduce((acc, key) => {\n const def = this.modelSchema.config.def[key];\n const paramKey = def.param;\n const paramValue = (parsedConfig as ConfigType)[key];\n\n if (paramKey === \"max_tokens\" && def.type === \"range\" && paramValue === 0) {\n acc[paramKey] = def.max;\n } else {\n acc[paramKey] = paramValue;\n }\n\n return acc;\n }, {} as ParamsType);\n\n if (transformedConfig.top_logprobs && !transformedConfig.logprobs) {\n throw new InvalidConfigError({\n info: `Invalid config for model : '${this.modelName}'`,\n cause: new Error(\"'logprobs' must be 'true' when 'top_logprobs' is specified\"),\n });\n }\n\n if (\"tool_choice\" in transformedConfig && transformedConfig.tool_choice !== undefined) {\n const toolChoice = transformedConfig.tool_choice as string;\n if (!tools || (tools && tools.length === 0)) {\n throw new InvalidConfigError({\n info: `Invalid config for model : '${this.modelName}'`,\n cause: new Error(\"'tools' are required when 'toolChoice' is specified\"),\n });\n } else if (tools && tools.length > 0) {\n const configToolChoice = this.modelSchema.config.def.toolChoice as SelectStringConfigItemDefType;\n if (!configToolChoice.choices.includes(toolChoice)) {\n if (tools.map((tool) => tool.definition.schema.name).includes(toolChoice)) {\n transformedConfig.tool_choice = { type: \"function\", function: { name: toolChoice } };\n } else {\n throw new InvalidConfigError({\n info: `Invalid config for model : '${this.modelName}'`,\n cause: new Error(`toolChoice : '${toolChoice}' is not part of provided 'tools' names or \n one of [${configToolChoice.choices.join(\", \")}]`),\n });\n }\n }\n }\n }\n\n if (\"response_format\" in transformedConfig && transformedConfig.response_format !== undefined) {\n const responseFormat = transformedConfig.response_format as string;\n if (responseFormat === \"json_schema\") {\n if (!(\"response_schema\" in transformedConfig)) {\n throw new InvalidConfigError({\n info: `Invalid config for model : '${this.modelName}'`,\n cause: new Error(\"'responseSchema' is required in config when 'responseFormat' is 'json_schema'\"),\n });\n } else {\n transformedConfig.response_format = {\n type: \"json_schema\",\n json_schema: transformedConfig.response_schema,\n };\n delete transformedConfig.response_schema;\n }\n } else {\n transformedConfig.response_format = { type: responseFormat };\n }\n }\n\n return transformedConfig;\n }\n\n transformMessages(messages: MessageType[]): ParamsType {\n if (!messages || (messages && messages.length === 0)) {\n return { messages: [] };\n }\n\n const parsedMessages = messages.map((message) => {\n const parsedMessage = Message().safeParse(message);\n if (!parsedMessage.success) {\n throw new InvalidMessagesError({ info: \"Invalid messages\", cause: parsedMessage.error });\n }\n return parsedMessage.data;\n });\n\n parsedMessages.forEach((message) => {\n message.content.forEach((content) => {\n if (!this.modelSchema.modalities.includes(content.modality)) {\n throw new InvalidMessagesError({\n info: `Invalid message content for model : '${this.modelName}'`,\n cause: new Error(`model : '${this.modelName}' does not support modality : '${content.modality}', \n available modalities : [${this.modelSchema.modalities.join(\", \")}]`),\n });\n }\n });\n });\n\n parsedMessages.forEach((message) => {\n if (!Object.keys(this.modelSchema.roles).includes(message.role)) {\n throw new InvalidMessagesError({\n info: `Invalid message content for model : '${this.modelName}'`,\n cause: new Error(`model : '${this.modelName}' does not support role : '${message.role}', \n available roles : [${Object.keys(this.modelSchema.roles).join(\", \")}]`),\n });\n }\n });\n\n const transformedMessages = parsedMessages.map((message) => {\n switch (message.role) {\n case SystemRoleLiteral: {\n const textContent: { type: \"text\"; text: string }[] = [];\n message.content.forEach((content) => {\n if (content.modality === TextModalityLiteral) {\n textContent.push({ type: \"text\", text: content.value });\n } else {\n throw new InvalidMessagesError({\n info: `Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,\n cause: new Error(`role : '${message.role}' cannot have content with modality : '${content.modality}'`),\n });\n }\n });\n\n return {\n role: this.modelSchema.roles[message.role],\n content: textContent,\n };\n }\n\n case AssistantRoleLiteral: {\n const textContent: { type: \"text\"; text: string }[] = [];\n const toolCalls: { id: string; type: \"function\"; function: { name: string; arguments: string } }[] = [];\n message.content.forEach((content) => {\n if (content.modality === TextModalityLiteral) {\n textContent.push({ type: \"text\", text: content.value });\n } else if (content.modality === ToolCallModalityLiteral) {\n toolCalls.push({\n id: content.id,\n type: \"function\",\n function: { name: content.name, arguments: content.arguments },\n });\n } else {\n throw new InvalidMessagesError({\n info: `Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,\n cause: new Error(`role : '${message.role}' cannot have content with modality : '${content.modality}'`),\n });\n }\n });\n\n return {\n role: this.modelSchema.roles[message.role],\n content: textContent,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n };\n }\n\n case UserRoleLiteral: {\n const textContent: { type: \"text\"; text: string }[] = [];\n const imageContent: { type: \"image_url\"; image_url: { url: string; detail: string } }[] = [];\n message.content.forEach((content) => {\n if (content.modality === TextModalityLiteral) {\n textContent.push({ type: \"text\", text: content.value });\n } else if (content.modality === ImageModalityLiteral) {\n imageContent.push({\n type: \"image_url\",\n image_url: {\n url: content.value.type === \"url\" ? content.value.url : content.value.base64,\n detail: content.detail,\n },\n });\n } else {\n throw new InvalidMessagesError({\n info: `Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,\n cause: new Error(`role : '${message.role}' cannot have content with modality : '${content.modality}'`),\n });\n }\n });\n\n const combinedContent = [...textContent, ...imageContent];\n\n return {\n role: this.modelSchema.roles[message.role],\n content: combinedContent,\n };\n }\n\n case ToolRoleLiteral: {\n if (message.content.length !== 1) {\n throw new InvalidMessagesError({\n info: `Invalid message for role : '${message.role}'`,\n cause: new Error(`role : '${message.role}' must have exactly one content item`),\n });\n }\n\n if (message.content[0].modality !== ToolResponseModalityLiteral) {\n throw new InvalidMessagesError({\n info: `Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,\n cause: new Error(`role : '${message.role}' must have content with modality : '${ToolResponseModalityLiteral}'`),\n });\n }\n\n const toolResponse = message.content[0] as ToolResponseContentType;\n return {\n role: this.modelSchema.roles[message.role],\n tool_call_id: toolResponse.id,\n content: toolResponse.data,\n };\n }\n\n default: {\n throw new InvalidMessagesError({\n info: `Invalid message 'role' for model : ${this.modelName}`,\n cause: new Error(`role : '${message.role}' is not supported, \n available roles : [${Object.keys(this.modelSchema.roles).join(\", \")}]`),\n });\n }\n }\n });\n\n return { messages: transformedMessages };\n }\n\n transformTools(tools: ToolType[]): ParamsType {\n if (!this.modelSchema.modalities.includes(ToolCallModalityLiteral)) {\n throw new InvalidToolsError({\n info: `Invalid tool 'modality' for model : ${this.modelName}`,\n cause: new Error(`model : '${this.modelName}' does not support tool modality : '${ToolCallModalityLiteral}'`),\n });\n }\n\n if (!tools || (tools && tools.length === 0)) {\n return { tools: [] as ToolType[] };\n }\n\n const parsedTools = tools.map((tool) => {\n const parsedTool = Tool().safeParse(tool);\n if (!parsedTool.success) {\n throw new InvalidToolsError({ info: \"Invalid tools\", cause: parsedTool.error });\n }\n return parsedTool.data;\n });\n\n const transformedTools = parsedTools.map((tool) => ({\n type: \"function\",\n function: tool.definition.schema,\n }));\n\n return { tools: transformedTools };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async getCompleteChatUrl(config?: ConfigType, messages?: MessageType[], tools?: ToolType[]): Promise<UrlType> {\n return new Promise((resolve) => {\n resolve(this.completeChatUrl);\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async getCompleteChatHeaders(config?: ConfigType, messages?: MessageType[], tools?: ToolType[]): Promise<HeadersType> {\n return new Promise((resolve) => {\n resolve(this.getDefaultHeaders());\n });\n }\n\n async getCompleteChatData(config: ConfigType, messages: MessageType[], tools?: ToolType[]): Promise<ParamsType> {\n const transformedConfig = this.transformConfig(config, messages, tools);\n const transformedMessages = this.transformMessages(messages);\n if (transformedMessages.messages && (transformedMessages.messages as MessageType[]).length === 0) {\n throw new InvalidMessagesError({\n info: \"Messages are required\",\n cause: new Error(\"Messages are required\"),\n });\n }\n\n const transformedTools = tools ? this.transformTools(tools) : {};\n\n return new Promise((resolve) => {\n resolve({\n ...this.getDefaultParams(),\n ...transformedConfig,\n ...transformedMessages,\n ...transformedTools,\n });\n });\n }\n\n transformCompleteChatResponse(response: any): ChatResponseType {\n const safe = OpenRouterCompleteChatResponse.safeParse(response);\n if (safe.success) {\n if (safe.data.choices.length === 0) {\n throw new ModelResponseError({\n info: \"Invalid response from model\",\n cause: new Error(`No choices in response : ${JSON.stringify(safe.data)}`),\n });\n }\n\n const parsedResponse: OpenRouterCompleteChatResponseType = safe.data;\n const messages: MessageType[] = [];\n const message = parsedResponse.choices[0].message;\n if (message.content) {\n messages.push(createTextMessage(AssistantRoleLiteral, message.content));\n }\n\n if (message.refusal) {\n messages.push(createTextMessage(AssistantRoleLiteral, message.refusal));\n }\n\n if (message.tool_calls) {\n message.tool_calls.forEach((toolCall, index) => {\n messages.push(\n createToolCallMessage(AssistantRoleLiteral, index, toolCall.id, toolCall.function.name, toolCall.function.arguments)\n );\n });\n }\n\n let usage: ChatUsageType | undefined;\n if (parsedResponse.usage) {\n usage = {\n promptTokens: parsedResponse.usage.prompt_tokens,\n completionTokens: parsedResponse.usage.completion_tokens,\n totalTokens: parsedResponse.usage.total_tokens,\n };\n }\n\n const logProbs: ChatLogProbsType = [];\n const _logProbs = parsedResponse.choices[0].logprobs;\n if (_logProbs) {\n if (_logProbs.content) {\n logProbs.push(\n ..._logProbs.content.map((logProb) => ({\n token: logProb.token,\n logProb: logProb.logprob,\n bytes: logProb.bytes,\n topLogProbs: logProb.top_logprobs.map((topLogProb) => ({\n token: topLogProb.token,\n logProb: topLogProb.logprob,\n bytes: topLogProb.bytes,\n })),\n }))\n );\n }\n if (_logProbs.refusal) {\n logProbs.push(\n ..._logProbs.refusal.map((logProb) => ({\n token: logProb.token,\n logProb: logProb.logprob,\n bytes: logProb.bytes,\n topLogProbs: logProb.top_logprobs.map((topLogProb) => ({\n token: topLogProb.token,\n logProb: topLogProb.logprob,\n bytes: topLogProb.bytes,\n })),\n }))\n );\n }\n }\n\n return {\n messages: messages,\n usage: usage,\n logProbs: logProbs,\n };\n }\n\n throw new ModelResponseError({ info: \"Invalid response from model\", cause: safe.error });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async getStreamChatUrl(config?: ConfigType, messages?: MessageType[], tools?: ToolType[]): Promise<UrlType> {\n return new Promise((resolve) => {\n resolve(this.streamChatUrl);\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async getStreamChatHeaders(config?: ConfigType, messages?: MessageType[], tools?: ToolType[]): Promise<HeadersType> {\n return new Promise((resolve) => {\n resolve(this.getDefaultHeaders());\n });\n }\n\n async getStreamChatData(config: ConfigType, messages: MessageType[], tools?: ToolType[]): Promise<ParamsType> {\n const transformedConfig = this.transformConfig(config, messages, tools);\n const transformedMessages = this.transformMessages(messages);\n if (transformedMessages.messages && (transformedMessages.messages as MessageType[]).length === 0) {\n throw new InvalidMessagesError({\n info: \"Messages are required\",\n cause: new Error(\"Messages are required\"),\n });\n }\n\n const transformedTools = tools ? this.transformTools(tools) : {};\n\n return new Promise((resolve) => {\n resolve({\n stream: true,\n stream_options: { include_usage: true },\n ...this.getDefaultParams(),\n ...transformedConfig,\n ...transformedMessages,\n ...transformedTools,\n });\n });\n }\n\n async *transformStreamChatResponseChunk(\n chunk: string,\n buffer: string\n ): AsyncGenerator<{ partialResponse: PartialChatResponseType; buffer: string }> {\n // merge last buffer message and split into lines\n const lines = (buffer + chunk).split(\"\\n\").filter((line) => line.trim() !== \"\");\n for (const line of lines) {\n if (line === \"data: [DONE]\") {\n // end of stream\n return;\n } else if (line.startsWith(\"data: {\") && line.endsWith(\"}\")) {\n // line contains message\n let structuredLine: any;\n try {\n // remove the 'data :' prefix from string JSON\n structuredLine = JSON.parse(line.substring(\"data: \".length));\n } catch (error) {\n // malformed JSON error\n throw new ModelResponseError({\n info: \"Malformed JSON received in stream\",\n cause: new Error(`Malformed JSON received in stream : ${structuredLine}`),\n });\n }\n\n const safe = OpenRouterStreamChatResponse.safeParse(structuredLine);\n if (safe.success) {\n const partialResponse: PartialChatResponseType = { partialMessages: [] };\n const parsedResponse: OpenRouterStreamChatResponseType = safe.data;\n if (parsedResponse.choices.length > 0) {\n const message = parsedResponse.choices[0].delta;\n if (message !== undefined && Object.keys(message).length !== 0) {\n if (\"content\" in message && message.content !== null) {\n partialResponse.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral, message.content as string));\n } else if (\"refusal\" in message && message.refusal !== null) {\n partialResponse.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral, message.refusal as string));\n } else if (\"tool_calls\" in message && message.tool_calls !== undefined) {\n const toolCall = message.tool_calls.at(0)!;\n partialResponse.partialMessages.push(\n createPartialToolCallMessage(\n AssistantRoleLiteral,\n toolCall.index,\n toolCall.id,\n toolCall.function?.name,\n toolCall.function?.arguments\n )\n );\n }\n }\n }\n\n if (parsedResponse.usage) {\n partialResponse.usage = {\n promptTokens: parsedResponse.usage.prompt_tokens,\n completionTokens: parsedResponse.usage.completion_tokens,\n totalTokens: parsedResponse.usage.total_tokens,\n };\n }\n\n yield { partialResponse: partialResponse, buffer: buffer };\n } else {\n throw new ModelResponseError({ info: \"Invalid response from model\", cause: safe.error });\n }\n } else {\n // line starts with unknown event -- ignore\n }\n }\n }\n}\n\nexport { BaseChatModel, type BaseChatModelOptionsType };\n","import { z } from \"zod\";\n\nimport { ChatModelSchema } from \"@adaline/provider\";\n\nimport { OpenRouterChatModelConfigs } from \"../../configs\";\n\nimport { \n OpenRouterChatModelRoles, \n OpenRouterChatModelRolesMap,\n OpenRouterChatModelModalities,\n OpenRouterChatModelModalitiesEnum,\n} from \"./types\";\n\nconst BaseChatModelSchema = ChatModelSchema(OpenRouterChatModelRoles, OpenRouterChatModelModalitiesEnum).parse({\n name: \"open-router-base-chat-model\",\n description: \"Base chat model for Open Router\",\n maxInputTokens: 128000,\n maxOutputTokens: 128000,\n roles: OpenRouterChatModelRolesMap,\n modalities: OpenRouterChatModelModalities,\n config: {\n def: OpenRouterChatModelConfigs.base(128000, 4).def,\n schema: OpenRouterChatModelConfigs.base(128000, 4).schema,\n },\n});\n\nexport { BaseChatModelSchema };"]}