@adaline/open-router 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +25 -24
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +8 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.d.mts
CHANGED
|
@@ -987,21 +987,21 @@ declare const BaseChatModelSchema: {
|
|
|
987
987
|
default: string | null;
|
|
988
988
|
choices: string[];
|
|
989
989
|
}>;
|
|
990
|
-
schema:
|
|
990
|
+
schema: zod.ZodObject<zod.ZodRawShape, zod.UnknownKeysParam, zod.ZodTypeAny, unknown, unknown>;
|
|
991
991
|
};
|
|
992
992
|
};
|
|
993
993
|
|
|
994
|
-
declare class OpenRouter<
|
|
994
|
+
declare class OpenRouter<C extends BaseChatModelOptionsType, E extends Record<string, any> = Record<string, any>> implements ProviderV1<C, E> {
|
|
995
995
|
readonly version: "v1";
|
|
996
996
|
readonly name = "open-router";
|
|
997
997
|
static readonly baseUrl = "https://openrouter.ai/api/v1";
|
|
998
998
|
private readonly embeddingModelFactories;
|
|
999
999
|
chatModelLiterals(): string[];
|
|
1000
1000
|
chatModelSchemas(): Record<string, ChatModelSchemaType>;
|
|
1001
|
-
chatModel(options:
|
|
1001
|
+
chatModel(options: C): ChatModelV1;
|
|
1002
1002
|
embeddingModelLiterals(): string[];
|
|
1003
1003
|
embeddingModelSchemas(): Record<string, EmbeddingModelSchemaType>;
|
|
1004
|
-
embeddingModel(options:
|
|
1004
|
+
embeddingModel(options: E): EmbeddingModelV1;
|
|
1005
1005
|
}
|
|
1006
1006
|
|
|
1007
|
-
export { BaseChatModel, type BaseChatModelOptionsType, BaseChatModelSchema, ChatModelBaseConfigDef, ChatModelBaseConfigSchema, OpenRouter, OpenRouterChatModelConfigs, frequencyPenalty, logProbs, maxTokens, minP, presencePenalty, repetitionPenalty, responseFormat, seed, stop, temperature, toolChoice, topA, topK, topLogProbs, topP };
|
|
1007
|
+
export { BaseChatModel, BaseChatModelOptions, type BaseChatModelOptionsType, BaseChatModelSchema, ChatModelBaseConfigDef, ChatModelBaseConfigSchema, OpenRouter, OpenRouterChatModelConfigs, frequencyPenalty, logProbs, maxTokens, minP, presencePenalty, repetitionPenalty, responseFormat, seed, stop, temperature, toolChoice, topA, topK, topLogProbs, topP };
|
package/dist/index.d.ts
CHANGED
|
@@ -987,21 +987,21 @@ declare const BaseChatModelSchema: {
|
|
|
987
987
|
default: string | null;
|
|
988
988
|
choices: string[];
|
|
989
989
|
}>;
|
|
990
|
-
schema:
|
|
990
|
+
schema: zod.ZodObject<zod.ZodRawShape, zod.UnknownKeysParam, zod.ZodTypeAny, unknown, unknown>;
|
|
991
991
|
};
|
|
992
992
|
};
|
|
993
993
|
|
|
994
|
-
declare class OpenRouter<
|
|
994
|
+
declare class OpenRouter<C extends BaseChatModelOptionsType, E extends Record<string, any> = Record<string, any>> implements ProviderV1<C, E> {
|
|
995
995
|
readonly version: "v1";
|
|
996
996
|
readonly name = "open-router";
|
|
997
997
|
static readonly baseUrl = "https://openrouter.ai/api/v1";
|
|
998
998
|
private readonly embeddingModelFactories;
|
|
999
999
|
chatModelLiterals(): string[];
|
|
1000
1000
|
chatModelSchemas(): Record<string, ChatModelSchemaType>;
|
|
1001
|
-
chatModel(options:
|
|
1001
|
+
chatModel(options: C): ChatModelV1;
|
|
1002
1002
|
embeddingModelLiterals(): string[];
|
|
1003
1003
|
embeddingModelSchemas(): Record<string, EmbeddingModelSchemaType>;
|
|
1004
|
-
embeddingModel(options:
|
|
1004
|
+
embeddingModel(options: E): EmbeddingModelV1;
|
|
1005
1005
|
}
|
|
1006
1006
|
|
|
1007
|
-
export { BaseChatModel, type BaseChatModelOptionsType, BaseChatModelSchema, ChatModelBaseConfigDef, ChatModelBaseConfigSchema, OpenRouter, OpenRouterChatModelConfigs, frequencyPenalty, logProbs, maxTokens, minP, presencePenalty, repetitionPenalty, responseFormat, seed, stop, temperature, toolChoice, topA, topK, topLogProbs, topP };
|
|
1007
|
+
export { BaseChatModel, BaseChatModelOptions, type BaseChatModelOptionsType, BaseChatModelSchema, ChatModelBaseConfigDef, ChatModelBaseConfigSchema, OpenRouter, OpenRouterChatModelConfigs, frequencyPenalty, logProbs, maxTokens, minP, presencePenalty, repetitionPenalty, responseFormat, seed, stop, temperature, toolChoice, topA, topK, topLogProbs, topP };
|
package/dist/index.js
CHANGED
|
@@ -2,35 +2,36 @@
|
|
|
2
2
|
|
|
3
3
|
var zod = require('zod');
|
|
4
4
|
|
|
5
|
-
var
|
|
6
|
-
Message: ${_t(n)}`),this.name=K,this.info=t,this.cause=n,this.name=a!=null?a:K,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof xe}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},j="system",I="user",v="assistant",k="tool",Pt=[j,I,v,k],H=zod.z.enum(Pt),St=[v],wt=zod.z.enum(St),x="image",G="base64",jt=["png","jpeg","webp","gif"],It=zod.z.object({type:zod.z.literal(G),base64:zod.z.string(),media_type:zod.z.enum(jt)}),V="url",kt=zod.z.object({type:zod.z.literal(V),url:zod.z.string()}),qt=zod.z.discriminatedUnion("type",[It,kt]),Lt=["low","medium","high","auto"],Nt=zod.z.enum(Lt),Ut=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(x),detail:Nt,value:qt,metadata:o}),C="text",_e=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(C),value:zod.z.string(),metadata:o}),Y="partial-text",Pe=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Y),value:zod.z.string(),metadata:o}),E="tool-call",Se=(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}),J="partial-tool-call",we=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(J),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",$t=(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}),Bt=[C,x,E,_],je=zod.z.enum(Bt),At=(o=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[_e(o),Ut(t),Se(n),$t(a)]),Ft=[Y,J];zod.z.enum(Ft);var zt=(o=zod.z.undefined(),t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Pe(o),we(t)]);var q=(o=H,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(At(t,n,a,r)),metadata:s}),W=(o=wt,t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined())=>zod.z.object({role:o,partialContent:zt(t,n),metadata:a});var Z=(o,t)=>q().parse({role:o,content:[_e().parse({modality:C,value:t})]});var Ie=(o,t,n,a,r)=>q().parse({role:o,content:[Se().parse({modality:E,index:t,id:n,name:a,arguments:r})]});var Q=(o,t)=>W().parse({role:o,partialContent:Pe().parse({modality:Y,value:t})}),ke=(o,t,n,a,r)=>W().parse({role:o,partialContent:we().parse({modality:J,index:t,id:n,name:a,arguments:r})});var qe=(o=zod.z.record(zod.z.string(),zod.z.any()).optional())=>o,Dt=["object","array","number","string","boolean","enum"],Oe=zod.z.enum(Dt),Kt=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([Oe,zod.z.array(zod.z.union([Oe,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()}),Ht=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(Kt),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:Ht}).optional();var Gt="function";var Vt=zod.z.enum(["object","array","number","string","boolean","null"]),Yt=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:Vt.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(Yt).optional(),required:zod.z.array(zod.z.string()).optional()});var Jt=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 Wt=zod.z.enum(["function"]),Zt=zod.z.object({type:Wt,definition:zod.z.object({schema:Jt})}),Qt=[Gt];zod.z.enum(Qt);var Le=(o=zod.z.undefined())=>zod.z.discriminatedUnion("type",[Zt.extend({metadata:o})]),Xt="text",eo="token",to=[Xt,eo];zod.z.enum(to);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var no="float",ao=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),so="base64",ro=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),Me=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(no),embeddings:zod.z.array(ao),usage:Me.optional()}),zod.z.object({encodingFormat:zod.z.literal(so),embeddings:zod.z.array(ro),usage:Me.optional()})]);var Ne=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Ee=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),io=Ee.extend({topLogProbs:zod.z.array(Ee)}),Ue=zod.z.array(io);zod.z.object({messages:zod.z.array(q()),usage:Ne.optional(),logProbs:Ue.optional()});zod.z.object({partialMessages:zod.z.array(W()),usage:Ne.optional(),logProbs:Ue.optional()});var lo=Object.defineProperty,$e=Object.getOwnPropertySymbols,po=Object.prototype.hasOwnProperty,mo=Object.prototype.propertyIsEnumerable,Be=(o,t,n)=>t in o?lo(o,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[t]=n,$=(o,t)=>{for(var n in t||(t={}))po.call(t,n)&&Be(o,n,t[n]);if($e)for(var n of $e(t))mo.call(t,n)&&Be(o,n,t[n]);return o},Ae="ProviderError",X=class Ge extends S{constructor({info:t,cause:n}){super({info:t,cause:n},Ae),this.name=Ae,this.info=t,this.cause=n;}static isProviderError(t){return t instanceof Ge}};var Fe="ModelResponseError",L=class Ve extends S{constructor({info:t,cause:n}){super({info:t,cause:n},Fe),this.name=Fe,this.cause=n,this.info=t;}static isModelResponseError(t){return t instanceof Ve}},ze="InvalidModelRequestError",B=class Ye extends S{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 isInvalidModelRequestError(t){return t instanceof Ye}},De="InvalidConfigError",w=class Je extends S{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 isInvalidConfigError(t){return t instanceof Je}},Ke="InvalidMessagesError",O=class We extends S{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 isInvalidMessagesError(t){return t instanceof We}},He="InvalidToolsError",ee=class Ze extends S{constructor({info:t,cause:n}){super({info:t,cause:n},He),this.name=He,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof Ze}};var te="multi-string",Qe=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()}),co=o=>zod.z.array(zod.z.string()).max(o).default([]).optional(),Xe=o=>({def:Qe.parse($({type:te},o)),schema:co(o.max)}),et="object-schema",uo=zod.z.object({type:zod.z.literal(et),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 oe="range",tt=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()}),ho=(o,t,n,a)=>zod.z.number().min(o).max(t).step(n).default(a).optional(),M=o=>({def:tt.parse($({type:oe},o)),schema:ho(o.min,o.max,o.step,o.default)}),ne="select-boolean",ot=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.boolean().nullable()}),fo=o=>zod.z.boolean().nullable().default(o).optional(),nt=o=>({def:ot.parse($({type:ne},o)),schema:fo(o.default)}),ae="select-string",at=zod.z.object({type:zod.z.literal(ae),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))}),go=(o,t)=>zod.z.enum(t).nullable().default(o).optional(),se=o=>({def:at.parse($({type:ae},o)),schema:go(o.default,o.choices)}),yo=[oe,te,ae,et,ne];zod.z.enum(yo);var bo=zod.z.discriminatedUnion("type",[tt,Qe,at,ot,uo]),st=(o=H,t=je)=>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),bo),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 To={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."},Co={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."},Ro=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.`}),vo={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."},Oo={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."},Mo={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."},Eo={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."},xo={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."},_o={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."},Po={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."},So={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."},wo={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."},jo={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."},Io={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},ko={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."},qo={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."},Lo={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:To,MAX_TOKENS:Co,STOP:Ro,TOP_A:vo,TOP_P:Oo,TOP_K:Mo,MIN_P:Eo,FREQUENCY_PENALTY:xo,PRESENCE_PENALTY:_o,REPETITION_PENALTY:So,SEED:Po,LOG_PROBS:wo,TOP_LOG_PROBS:jo,ECHO:Io,RESPONSE_FORMAT:ko,RESPONSE_FORMAT_WITH_SCHEMA:qo,RESPONSE_SCHEMA:Lo};var rt=o=>Object.fromEntries(Object.entries(o).filter(([t,n])=>n!=null));var it=o=>o.split(";")[0].split("/")[1],A=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=>Xe({param:"stop",title:f.STOP(o).title,description:f.STOP(o).description,max:o}),Rn=M({param:"top_a",title:f.TOP_A.title,description:f.TOP_A.description,min:0,max:1,step:.01,default:0}),vn=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}),On=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}),Mn=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=se({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"]}),En=se({param:"response_format",title:f.RESPONSE_FORMAT.title,description:f.RESPONSE_FORMAT.description,default:"text",choices:["text","json_object"]});var lt=(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}),pt=(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:pt(o,t),schema:lt(o,t)})};var Uo="open-router",N=class{constructor(){this.version="v1";this.name=Uo;this.embeddingModelFactories={};}chatModelLiterals(){return ["base"]}chatModelSchemas(){return {base:ye}}chatModel(t){let n=t.modelName;if(!n)throw new X({info:"options.modelName is required",cause:new Error("options.modelName is required")});let a=Re(R({},t),{modelName:n});return new F(ye,a)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,n)=>(t[n]=this.embeddingModelFactories[n].modelSchema,t),{})}embeddingModel(t){throw new X({info:"Open Router does not support embedding models",cause:new Error("Open Router does not support embedding models")})}};N.baseUrl="https://openrouter.ai/api/v1";var mt=zod.z.enum([j,I,v,k]),ct={system:j,user:I,assistant:v,tool:k};var dt=[C,x,E,_],ut=zod.z.enum([C,x,E,_]);var z=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),ht=zod.z.object({content:zod.z.array(z.extend({top_logprobs:zod.z.array(z)})).nullable(),refusal:zod.z.array(z.extend({top_logprobs:zod.z.array(z)})).nullable()}).nullable(),Ao=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()})})),ft=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:Ao.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:ht.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()}),Fo=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()})),gt=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:Fo.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:ht,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 zo=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()})}),Do=zod.z.enum(["none","auto","required"]),Ko=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),Ho=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")}),Go=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()})}),Vo=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)})}),Yo=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(be).min(1))}),Jo=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([be,Go])).min(1))}),Wo=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(Vo).min(1).optional()}),Zo=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),Qo=zod.z.union([Yo,Jo,Wo,Zo]),yt=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(Qo).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:Ho.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(zo).optional(),tool_choice:Do.or(Ko).optional()});var Xo=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),openRouterReferer:zod.z.string().optional(),openRouterTitle:zod.z.string().optional()}),F=class{constructor(t,n){this.version="v1";let a=Xo.parse(n);this.modelSchema=t,this.modelName=a.modelName,this.apiKey=a.apiKey,this.baseUrl=A(N.baseUrl),this.streamChatUrl=A(`${this.baseUrl}/chat/completions`),this.completeChatUrl=A(`${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=yt.safeParse(t);if(!n.success)throw new B({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 B({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=qe().parse(rt(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:C,value:g}]});else {let b=g.map(T=>({modality:C,value:T.text}));p.push({role:y,content:b});}}break;case"user":{let g=u.content;if(typeof g=="string")p.push({role:y,content:[{modality:C,value:g}]});else {let b=g.map(T=>T.type==="text"?{modality:C,value:T.text}:T.image_url.url.startsWith("data:")?{modality:x,detail:T.image_url.detail||"auto",value:{type:G,base64:T.image_url.url,media_type:it(T.image_url.url)}}:{modality:x,detail:T.image_url.detail||"auto",value:{type:V,url:T.image_url.url}});p.push({role:y,content:b});}}break;case"assistant":{let g=[];if(!u.content&&!u.tool_calls)throw new B({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:C,value:b}):b.forEach(T=>{g.push({modality:C,value:T.text});});}u.tool_calls&&u.tool_calls.forEach((T,bt)=>{let D={modality:E,id:T.id,index:bt,name:T.function.name,arguments:T.function.arguments};g.push(D),c[D.id]=D;}),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 w({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 w({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${c}',
|
|
5
|
+
var Ct=Object.defineProperty;var Ce=Object.getOwnPropertySymbols;var Tt=Object.prototype.hasOwnProperty,Rt=Object.prototype.propertyIsEnumerable;var vt=(o,t)=>(t=Symbol[o])?t:Symbol.for("Symbol."+o);var Te=(o,t,n)=>t in o?Ct(o,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[t]=n,v=(o,t)=>{for(var n in t||(t={}))Tt.call(t,n)&&Te(o,n,t[n]);if(Ce)for(var n of Ce(t))Rt.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());}),Mt=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 Mt,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[vt("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})},Et=o=>o==null?"unknown error":typeof o=="string"?o:o instanceof Error?o.message:Ot(o),K="GatewayBaseError",S=class Ee extends Error{constructor({info:t,cause:n},a){super(`[${a!=null?a:K}]: ${t}
|
|
6
|
+
Message: ${Et(n)}`),this.name=K,this.info=t,this.cause=n,this.name=a!=null?a:K,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}}},j="system",I="user",R="assistant",k="tool",_t=[j,I,R,k],H=zod.z.enum(_t),xt=[R],Pt=zod.z.enum(xt),_="image",G="base64",St=["png","jpeg","webp","gif"],wt=zod.z.object({type:zod.z.literal(G),base64:zod.z.string(),media_type:zod.z.enum(St)}),V="url",jt=zod.z.object({type:zod.z.literal(V),url:zod.z.string()}),It=zod.z.discriminatedUnion("type",[wt,jt]),kt=["low","medium","high","auto"],qt=zod.z.enum(kt),Lt=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(_),detail:qt,value:It,metadata:o}),T="text",_e=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(T),value:zod.z.string(),metadata:o}),Y="partial-text",xe=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Y),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}),J="partial-tool-call",Se=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(J),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:o}),x="tool-response",Nt=(o=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(x),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:o}),Ut=[T,_,E,x],we=zod.z.enum(Ut),$t=(o=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[_e(o),Lt(t),Pe(n),Nt(a)]),Bt=[Y,J];zod.z.enum(Bt);var At=(o=zod.z.undefined(),t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[xe(o),Se(t)]);var q=(o=H,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($t(t,n,a,r)),metadata:s}),W=(o=Pt,t=zod.z.undefined(),n=zod.z.undefined(),a=zod.z.undefined())=>zod.z.object({role:o,partialContent:At(t,n),metadata:a});var Z=(o,t)=>q().parse({role:o,content:[_e().parse({modality:T,value:t})]});var je=(o,t,n,a,r)=>q().parse({role:o,content:[Pe().parse({modality:E,index:t,id:n,name:a,arguments:r})]});var Q=(o,t)=>W().parse({role:o,partialContent:xe().parse({modality:Y,value:t})}),Ie=(o,t,n,a,r)=>W().parse({role:o,partialContent:Se().parse({modality:J,index:t,id:n,name:a,arguments:r})});var ke=(o=zod.z.record(zod.z.string(),zod.z.any()).optional())=>o,Ft=["object","array","number","string","boolean","enum"],ve=zod.z.enum(Ft),zt=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()}),Dt=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(zt),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:Dt}).optional();var Kt="function";var Ht=zod.z.enum(["object","array","number","string","boolean","null"]),Gt=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:Ht.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(Gt).optional(),required:zod.z.array(zod.z.string()).optional()});var Vt=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"]),Jt=zod.z.object({type:Yt,definition:zod.z.object({schema:Vt})}),Wt=[Kt];zod.z.enum(Wt);var qe=(o=zod.z.undefined())=>zod.z.discriminatedUnion("type",[Jt.extend({metadata:o})]),Zt="text",Qt="token",Xt=[Zt,Qt];zod.z.enum(Xt);zod.z.array(zod.z.string().min(1));zod.z.array(zod.z.array(zod.z.number().int().nonnegative()));var to="float",oo=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),no="base64",ao=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),Me=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(to),embeddings:zod.z.array(oo),usage:Me.optional()}),zod.z.object({encodingFormat:zod.z.literal(no),embeddings:zod.z.array(ao),usage:Me.optional()})]);var Le=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),Oe=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),so=Oe.extend({topLogProbs:zod.z.array(Oe)}),Ne=zod.z.array(so);zod.z.object({messages:zod.z.array(q()),usage:Le.optional(),logProbs:Ne.optional()});zod.z.object({partialMessages:zod.z.array(W()),usage:Le.optional(),logProbs:Ne.optional()});var ro=Object.defineProperty,Ue=Object.getOwnPropertySymbols,io=Object.prototype.hasOwnProperty,lo=Object.prototype.propertyIsEnumerable,$e=(o,t,n)=>t in o?ro(o,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[t]=n,$=(o,t)=>{for(var n in t||(t={}))io.call(t,n)&&$e(o,n,t[n]);if(Ue)for(var n of Ue(t))lo.call(t,n)&&$e(o,n,t[n]);return o},Be="ProviderError",He=class Ge extends S{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 Ge}};var Ae="ModelResponseError",L=class Ve extends S{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 Ve}},Fe="InvalidModelRequestError",B=class Ye extends S{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",w=class Je extends S{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 Je}},De="InvalidMessagesError",M=class We extends S{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 We}},Ke="InvalidToolsError",X=class Ze extends S{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 Ze}};var ee="multi-string",Qe=zod.z.object({type:zod.z.literal(ee),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()}),po=o=>zod.z.array(zod.z.string()).max(o).default([]).optional(),Xe=o=>({def:Qe.parse($({type:ee},o)),schema:po(o.max)}),et="object-schema",mo=zod.z.object({type:zod.z.literal(et),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 te="range",tt=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),min:zod.z.number().int(),max:zod.z.number().int(),step:zod.z.number().positive(),default:zod.z.number()}),co=(o,t,n,a)=>zod.z.number().min(o).max(t).step(n).default(a).optional(),O=o=>({def:tt.parse($({type:te},o)),schema:co(o.min,o.max,o.step,o.default)}),oe="select-boolean",ot=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),default:zod.z.boolean().nullable()}),uo=o=>zod.z.boolean().nullable().default(o).optional(),nt=o=>({def:ot.parse($({type:oe},o)),schema:uo(o.default)}),ne="select-string",at=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))}),ho=(o,t)=>zod.z.enum(t).nullable().default(o).optional(),ae=o=>({def:at.parse($({type:ne},o)),schema:ho(o.default,o.choices)}),fo=[te,ee,ne,et,oe];zod.z.enum(fo);var go=zod.z.discriminatedUnion("type",[tt,Qe,at,ot,mo]),st=(o=H,t=we)=>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),go),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 yo={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."},bo={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."},Co=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.`}),To={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."},Ro={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."},vo={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."},Mo={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."},Eo={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."},_o={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."},Po={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."},So={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."},jo={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."},Io={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."},ko={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:yo,MAX_TOKENS:bo,STOP:Co,TOP_A:To,TOP_P:Ro,TOP_K:vo,MIN_P:Mo,FREQUENCY_PENALTY:Oo,PRESENCE_PENALTY:Eo,REPETITION_PENALTY:xo,SEED:_o,LOG_PROBS:Po,TOP_LOG_PROBS:So,ECHO:wo,RESPONSE_FORMAT:jo,RESPONSE_FORMAT_WITH_SCHEMA:Io,RESPONSE_SCHEMA:ko};var rt=o=>Object.fromEntries(Object.entries(o).filter(([t,n])=>n!=null));var it=o=>o.split(";")[0].split("/")[1],A=o=>o==null?void 0:o.replace(/\/$/,"");var se=O({param:"temperature",title:f.TEMPERATURE.title,description:f.TEMPERATURE.description,min:0,max:2,step:.01,default:1}),re=o=>O({param:"max_tokens",title:f.MAX_TOKENS.title,description:f.MAX_TOKENS.description,min:0,max:o,step:1,default:0}),ie=o=>Xe({param:"stop",title:f.STOP(o).title,description:f.STOP(o).description,max:o}),bn=O({param:"top_a",title:f.TOP_A.title,description:f.TOP_A.description,min:0,max:1,step:.01,default:0}),Cn=O({param:"top_k",title:f.TOP_K.title,description:f.TOP_K.description,min:0,max:100,step:1,default:0}),le=O({param:"top_p",title:f.TOP_P.title,description:f.TOP_P.description,min:0,max:1,step:.01,default:1}),Tn=O({param:"min_p",title:f.MIN_P.title,description:f.MIN_P.description,min:0,max:1,step:.01,default:0}),pe=O({param:"frequency_penalty",title:f.FREQUENCY_PENALTY.title,description:f.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),me=O({param:"presence_penalty",title:f.PRESENCE_PENALTY.title,description:f.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),Rn=O({param:"repetition_penalty",title:f.REPETITION_PENALTY.title,description:f.REPETITION_PENALTY.description,min:0,max:2,step:.01,default:0}),ce=O({param:"seed",title:f.SEED.title,description:f.SEED.description,min:0,max:1e6,step:1,default:0}),de=nt({param:"logprobs",title:f.LOG_PROBS.title,description:f.LOG_PROBS.description,default:!1}),ue=O({param:"top_logprobs",title:f.TOP_LOG_PROBS.title,description:f.TOP_LOG_PROBS.description,min:0,max:20,step:1,default:0}),he=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 lt=(o,t)=>zod.z.object({temperature:se.schema,maxTokens:re(o).schema,stop:ie(t).schema,topP:le.schema,frequencyPenalty:pe.schema,presencePenalty:me.schema,seed:ce.schema.transform(n=>n===0?void 0:n),logProbs:de.schema,topLogProbs:ue.schema,toolChoice:he.schema}),pt=(o,t)=>({temperature:se.def,maxTokens:re(o).def,stop:ie(t).def,topP:le.def,frequencyPenalty:pe.def,presencePenalty:me.def,seed:ce.def,logProbs:de.def,topLogProbs:ue.def,toolChoice:he.def});var fe={base:(o,t)=>({def:pt(o,t),schema:lt(o,t)})};var Lo="open-router",N=class{constructor(){this.version="v1";this.name=Lo;this.embeddingModelFactories={};}chatModelLiterals(){return ["__base__"]}chatModelSchemas(){return {__base__:ge}}chatModel(t){let n=F,a=ye.parse(t);return new n(ge,a)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,n)=>(t[n]=this.embeddingModelFactories[n].modelSchema,t),{})}embeddingModel(t){throw new He({info:"Open Router does not support embedding models yet",cause:new Error("Open Router does not support embedding models yet")})}};N.baseUrl="https://openrouter.ai/api/v1";var mt=zod.z.enum([j,I,R,k]),ct={system:j,user:I,assistant:R,tool:k};var dt=[T,_,E,x],ut=zod.z.enum([T,_,E,x]);var z=zod.z.object({token:zod.z.string(),logprob:zod.z.number(),bytes:zod.z.array(zod.z.number()).nullable()}),ht=zod.z.object({content:zod.z.array(z.extend({top_logprobs:zod.z.array(z)})).nullable(),refusal:zod.z.array(z.extend({top_logprobs:zod.z.array(z)})).nullable()}).nullable(),$o=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()})})),ft=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:$o.optional(),refusal:zod.z.string().nullable().optional()}),logprobs:ht.optional(),finish_reason:zod.z.string().nullable().optional()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()}).nullable().optional()}),Bo=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()})),gt=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:Bo.optional(),refusal:zod.z.string().nullable().optional()}).or(zod.z.object({})),logprobs:ht,finish_reason:zod.z.string().nullable().optional()})),usage:zod.z.object({prompt_tokens:zod.z.number(),completion_tokens:zod.z.number(),total_tokens:zod.z.number()}).nullable().optional()});var Ao=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()})}),Fo=zod.z.enum(["none","auto","required"]),zo=zod.z.object({type:zod.z.literal("function"),function:zod.z.object({name:zod.z.string().min(1)})}),Do=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")}),Ko=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()})}),Ho=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)})}),Go=zod.z.object({role:zod.z.literal("system"),content:zod.z.string().min(1).or(zod.z.array(be).min(1))}),Vo=zod.z.object({role:zod.z.literal("user"),content:zod.z.string().min(1).or(zod.z.array(zod.z.union([be,Ko])).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(Ho).min(1).optional()}),Jo=zod.z.object({role:zod.z.literal("tool"),tool_call_id:zod.z.string().min(1),content:zod.z.string().min(1)}),Wo=zod.z.union([Go,Vo,Yo,Jo]),yt=zod.z.object({model:zod.z.string().min(1).optional(),messages:zod.z.array(Wo).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:Do.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(Ao).optional(),tool_choice:Fo.or(zo).optional()});var ye=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),openRouterReferer:zod.z.string().optional(),openRouterTitle:zod.z.string().optional()}),F=class{constructor(t,n){this.version="v1";let a=ye.parse(n);this.modelSchema=t,this.modelName=a.modelName,this.apiKey=a.apiKey,this.baseUrl=A(N.baseUrl),this.streamChatUrl=A(`${this.baseUrl}/chat/completions`),this.completeChatUrl=A(`${this.baseUrl}/chat/completions`),this.openRouterReferer=a.openRouterReferer,this.openRouterTitle=a.openRouterTitle;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return v(v({Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},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=yt.safeParse(t);if(!n.success)throw new B({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 B({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(rt(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:_,detail:C.image_url.detail||"auto",value:{type:G,base64:C.image_url.url,media_type:it(C.image_url.url)}}:{modality:_,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 B({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,bt)=>{let D={modality:E,id:C.id,index:bt,name:C.function.name,arguments:C.function.arguments};g.push(D),c[D.id]=D;}),p.push({role:y,content:g});}break;case"tool":{let g=u;p.push({role:y,content:[{modality:x,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 w({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 w({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${c}',
|
|
7
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 w({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 w({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 w({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 w({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=q().safeParse(r);if(!s.success)throw new
|
|
9
|
-
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),n.forEach(r=>{if(!Object.keys(this.modelSchema.roles).includes(r.role))throw new
|
|
10
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),{messages:n.map(r=>{switch(r.role){case j:{let s=[];return r.content.forEach(d=>{if(d.modality===
|
|
11
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}})}}transformTools(t){if(!this.modelSchema.modalities.includes(E))throw new
|
|
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 L({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${p}`)})}let c=gt.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(Q(
|
|
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 w({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=q().safeParse(r);if(!s.success)throw new M({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 M({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 M({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 j:{let s=[];return r.content.forEach(d=>{if(d.modality===T)s.push({type:"text",text:d.value});else throw new M({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 R:{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 M({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${p.modality}'`)})}),v({role:this.modelSchema.roles[r.role],content:s},d.length>0?{tool_calls:d}:{})}case I:{let s=[],d=[];r.content.forEach(c=>{if(c.modality===T)s.push({type:"text",text:c.value});else if(c.modality===_)d.push({type:"image_url",image_url:{url:c.value.type==="url"?c.value.url:c.value.base64,detail:c.detail}});else throw new M({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 k:{if(r.content.length!==1)throw new M({info:`Invalid message for role : '${r.role}'`,cause:new Error(`role : '${r.role}' must have exactly one content item`)});if(r.content[0].modality!==x)throw new M({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' must have content with modality : '${x}'`)});let s=r.content[0];return {role:this.modelSchema.roles[r.role],tool_call_id:s.id,content:s.data}}default:throw new M({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 X({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 X({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 M({info:"Messages are required",cause:new Error("Messages are required")});let d=a?this.transformTools(a):{};return new Promise(p=>{p(v(v(v(v({},this.getDefaultParams()),r),s),d));})})}transformCompleteChatResponse(t){let n=ft.safeParse(t);if(n.success){if(n.data.choices.length===0)throw new L({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(Z(R,s.content)),s.refusal&&r.push(Z(R,s.refusal)),s.tool_calls&&s.tool_calls.forEach((h,u)=>{r.push(je(R,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 L({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 M({info:"Messages are required",cause:new Error("Messages are required")});let d=a?this.transformTools(a):{};return new Promise(p=>{p(v(v(v(v({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 L({info:"Malformed JSON received in stream",cause:new Error(`Malformed JSON received in stream : ${p}`)})}let c=gt.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(Q(R,y.content));else if("refusal"in y&&y.refusal!==null)h.partialMessages.push(Q(R,y.refusal));else if("tool_calls"in y&&y.tool_calls!==void 0){let g=y.tool_calls.at(0);h.partialMessages.push(Ie(R,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 L({info:"Invalid response from model",cause:c.error})}}})}};var ge=st(mt,ut).parse({name:"__base__",description:"Base chat model for Open Router",maxInputTokens:128e3,maxOutputTokens:128e3,roles:ct,modalities:dt,config:{def:fe.base(128e3,4).def,schema:fe.base(128e3,4).schema}});
|
|
13
13
|
|
|
14
14
|
exports.BaseChatModel = F;
|
|
15
|
-
exports.
|
|
15
|
+
exports.BaseChatModelOptions = ye;
|
|
16
|
+
exports.BaseChatModelSchema = ge;
|
|
16
17
|
exports.ChatModelBaseConfigDef = pt;
|
|
17
18
|
exports.ChatModelBaseConfigSchema = lt;
|
|
18
19
|
exports.OpenRouter = N;
|
|
19
|
-
exports.OpenRouterChatModelConfigs =
|
|
20
|
-
exports.frequencyPenalty =
|
|
21
|
-
exports.logProbs =
|
|
22
|
-
exports.maxTokens =
|
|
23
|
-
exports.minP =
|
|
24
|
-
exports.presencePenalty =
|
|
25
|
-
exports.repetitionPenalty =
|
|
26
|
-
exports.responseFormat =
|
|
27
|
-
exports.seed =
|
|
28
|
-
exports.stop =
|
|
29
|
-
exports.temperature =
|
|
30
|
-
exports.toolChoice =
|
|
31
|
-
exports.topA =
|
|
32
|
-
exports.topK =
|
|
33
|
-
exports.topLogProbs =
|
|
34
|
-
exports.topP =
|
|
20
|
+
exports.OpenRouterChatModelConfigs = fe;
|
|
21
|
+
exports.frequencyPenalty = pe;
|
|
22
|
+
exports.logProbs = de;
|
|
23
|
+
exports.maxTokens = re;
|
|
24
|
+
exports.minP = Tn;
|
|
25
|
+
exports.presencePenalty = me;
|
|
26
|
+
exports.repetitionPenalty = Rn;
|
|
27
|
+
exports.responseFormat = vn;
|
|
28
|
+
exports.seed = ce;
|
|
29
|
+
exports.stop = ie;
|
|
30
|
+
exports.temperature = se;
|
|
31
|
+
exports.toolChoice = he;
|
|
32
|
+
exports.topA = bn;
|
|
33
|
+
exports.topK = Cn;
|
|
34
|
+
exports.topLogProbs = ue;
|
|
35
|
+
exports.topP = le;
|
|
35
36
|
//# sourceMappingURL=index.js.map
|
|
36
37
|
//# sourceMappingURL=index.js.map
|