@adaline/vertex 0.7.0 → 0.8.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 +7 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +7 -7
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -3,18 +3,18 @@
|
|
|
3
3
|
var zod = require('zod');
|
|
4
4
|
|
|
5
5
|
var $n=Object.defineProperty,qn=Object.defineProperties;var Bn=Object.getOwnPropertyDescriptors;var Gt=Object.getOwnPropertySymbols;var Un=Object.prototype.hasOwnProperty,An=Object.prototype.propertyIsEnumerable;var Pt=(t,e,o)=>e in t?$n(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,ne=(t,e)=>{for(var o in e||(e={}))Un.call(e,o)&&Pt(t,o,e[o]);if(Gt)for(var o of Gt(e))An.call(e,o)&&Pt(t,o,e[o]);return t},wt=(t,e)=>qn(t,Bn(e));var he=(t,e,o)=>new Promise((i,s)=>{var r=c=>{try{m(o.next(c));}catch(p){s(p);}},d=c=>{try{m(o.throw(c));}catch(p){s(p);}},m=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,d);m((o=o.apply(t,e)).next());});var Dn=t=>{let e=new WeakSet;return JSON.stringify(t,(o,i)=>{if(typeof i=="object"&&i!==null){if(e.has(i))return;e.add(i);}return i})},Vn=t=>t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:Dn(t),Je="GatewayBaseError",B=class Rt extends Error{constructor({info:e,cause:o},i){super(`[${i!=null?i:Je}]: ${e}
|
|
6
|
-
Message: ${Vn(o)}`),this.name=Je,this.info=e,this.cause=o,this.name=i!=null?i:Je,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(e){return e instanceof Rt}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},de="system",I="user",L="assistant",Q="tool",zn=[de,I,L,Q],We=zod.z.enum(zn),Hn=[L],Kn=zod.z.enum(Hn),U="image",Ze="base64",Yn=["png","jpeg","webp","gif"],Jn=zod.z.object({type:zod.z.literal(Ze),base64:zod.z.string(),media_type:zod.z.enum(Yn)}),Wn="url",Zn=zod.z.object({type:zod.z.literal(Wn),url:zod.z.string()}),Xn=zod.z.discriminatedUnion("type",[Jn,Zn]),Qn=["low","medium","high","auto"],ea=zod.z.enum(Qn),ta=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(U),detail:ea,value:Xn,metadata:t}),_="text",Nt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(_),value:zod.z.string(),metadata:t}),Xe="partial-text",Lt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Xe),value:zod.z.string(),metadata:t}),w="tool-call",Ft=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(w),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),Qe="partial-tool-call",$t=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Qe),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),A="tool-response",oa=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(A),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),na=[_,U,w,A],qt=zod.z.enum(na),aa=(t=zod.z.undefined(),e=zod.z.undefined(),o=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Nt(t),ta(e),Ft(o),oa(i)]),ia=[Xe,Qe];zod.z.enum(ia);var sa=(t=zod.z.undefined(),e=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Lt(t),$t(e)]);var et=(t=We,e=zod.z.undefined(),o=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(aa(e,o,i,s)),metadata:r}),tt=(t=Kn,e=zod.z.undefined(),o=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:sa(e,o),metadata:i}),Bt=t=>Nt().parse({modality:_,value:t}),Ut=(t,e,o,i)=>Ft().parse({modality:w,index:t,id:e,name:o,arguments:i});var At=(t,e)=>tt().parse({role:t,partialContent:Lt().parse({modality:Xe,value:e})}),Dt=(t,e,o,i,s)=>tt().parse({role:t,partialContent:$t().parse({modality:Qe,index:e,id:o,name:i,arguments:s})});var ce=(t=zod.z.record(zod.z.string(),zod.z.any()).optional())=>t,ra=["object","array","number","string","boolean","enum"],kt=zod.z.enum(ra),la=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([kt,zod.z.array(zod.z.union([kt,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()}),ma=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(la),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:ma}).optional();var da="function";var ca=zod.z.enum(["object","array","number","string","boolean","null"]),pa=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:ca.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(pa).optional(),required:zod.z.array(zod.z.string()).optional()});var ua=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 ga=zod.z.enum(["function"]),ha=zod.z.object({type:ga,definition:zod.z.object({schema:ua})}),fa=[da];zod.z.enum(fa);var Vt=(t=zod.z.undefined())=>zod.z.discriminatedUnion("type",[ha.extend({metadata:t})]),M="text",zt="token",ya=[M,zt],Ht=zod.z.enum(ya),ba=zod.z.array(zod.z.string().min(1)),_a=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),fe=(t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(M),metadata:t,requests:ba}),zod.z.object({modality:zod.z.literal(zt),metadata:t,requests:_a})]),pe="float",Ea=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),Ta="base64",Ma=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),It=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(pe),embeddings:zod.z.array(Ea),usage:It.optional()}),zod.z.object({encodingFormat:zod.z.literal(Ta),embeddings:zod.z.array(Ma),usage:It.optional()})]);var Kt=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),jt=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),xa=jt.extend({topLogProbs:zod.z.array(jt)}),Yt=zod.z.array(xa);zod.z.object({messages:zod.z.array(et()),usage:Kt.optional(),logProbs:Yt.optional()});zod.z.object({partialMessages:zod.z.array(tt()),usage:Kt.optional(),logProbs:Yt.optional()});var va=Object.defineProperty,Jt=Object.getOwnPropertySymbols,Ca=Object.prototype.hasOwnProperty,Oa=Object.prototype.propertyIsEnumerable,Wt=(t,e,o)=>e in t?va(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,ue=(t,e)=>{for(var o in e||(e={}))Ca.call(e,o)&&Wt(t,o,e[o]);if(Jt)for(var o of Jt(e))Oa.call(e,o)&&Wt(t,o,e[o]);return t},Zt="ProviderError",ae=class io extends B{constructor({info:e,cause:o}){super({info:e,cause:o},Zt),this.name=Zt,this.info=e,this.cause=o;}static isProviderError(e){return e instanceof io}},Xt="ModelError",ye=class so extends B{constructor({info:e,cause:o}){super({info:e,cause:o},Xt),this.name=Xt,this.info=e,this.cause=o;}static isModelError(e){return e instanceof so}},Qt="ModelResponseError",D=class ro extends B{constructor({info:e,cause:o}){super({info:e,cause:o},Qt),this.name=Qt,this.cause=o,this.info=e;}static isModelResponseError(e){return e instanceof ro}},eo="InvalidModelRequestError",V=class lo extends B{constructor({info:e,cause:o}){super({info:e,cause:o},eo),this.name=eo,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(e){return e instanceof lo}},to="InvalidConfigError",F=class mo extends B{constructor({info:e,cause:o}){super({info:e,cause:o},to),this.name=to,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(e){return e instanceof mo}},oo="InvalidMessagesError",T=class co extends B{constructor({info:e,cause:o}){super({info:e,cause:o},oo),this.name=oo,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(e){return e instanceof co}},no="InvalidToolsError",ot=class po extends B{constructor({info:e,cause:o}){super({info:e,cause:o},no),this.name=no,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(e){return e instanceof po}},ao="InvalidEmbeddingRequestsError",Y=class uo extends B{constructor({info:e,cause:o}){super({info:e,cause:o},ao),this.name=ao,this.info=e,this.cause=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(e){return e instanceof uo}},nt="multi-string",go=zod.z.object({type:zod.z.literal(nt),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()}),Sa=t=>zod.z.array(zod.z.string()).max(t).default([]).optional(),ho=t=>({def:go.parse(ue({type:nt},t)),schema:Sa(t.max)}),at="object-schema",fo=zod.z.object({type:zod.z.literal(at),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),objectSchema:zod.z.any()}),Ga=t=>t.optional(),yo=t=>({def:fo.parse(ue({type:at},t)),schema:Ga(t.objectSchema)}),it="range",bo=zod.z.object({type:zod.z.literal(it),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()}),Pa=(t,e,o,i)=>zod.z.number().min(t).max(e).step(o).default(i).optional(),j=t=>({def:bo.parse(ue({type:it},t)),schema:Pa(t.min,t.max,t.step,t.default)}),st="select-boolean",_o=zod.z.object({type:zod.z.literal(st),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()}),wa=t=>zod.z.boolean().nullable().default(t).optional(),Eo=t=>({def:_o.parse(ue({type:st},t)),schema:wa(t.default)}),rt="select-string",To=zod.z.object({type:zod.z.literal(rt),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))}),ka=(t,e)=>zod.z.enum(e).nullable().default(t).optional(),Mo=t=>({def:To.parse(ue({type:rt},t)),schema:ka(t.default,t.choices)}),Ia=[it,nt,rt,at,st];zod.z.enum(Ia);var xo=zod.z.discriminatedUnion("type",[bo,go,To,_o,fo]),x=(t=We,e=qt)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(t,zod.z.string().min(1).optional()),modalities:zod.z.array(e).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),xo),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(o=>{var i,s;let r=Object.keys(o.def),d=Object.keys((s=(i=o.schema)==null?void 0:i.shape)!=null?s:{});return r.every(m=>d.includes(m))&&d.every(m=>r.includes(m))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),R=(t=Ht)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),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),xo),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(e=>{var o,i;let s=Object.keys(e.def),r=Object.keys((i=(o=e.schema)==null?void 0:o.shape)!=null?i:{});return s.every(d=>r.includes(d))&&r.every(d=>s.includes(d))},{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 ja={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."},Ra={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."},Na=t=>({type:"multi",title:"Stop sequence",description:`Enter up to ${t} sequences that will halt additional text output. The generated text will exclude these sequences.`}),La={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."},Fa={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."},$a={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."},qa={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."},Ba={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."},Ua={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."},Aa={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."},Da={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."},Va={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."},za={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."},Ha={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},Ka={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."},Ya={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."},Ja={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."},E={TEMPERATURE:ja,MAX_TOKENS:Ra,STOP:Na,TOP_A:La,TOP_P:Fa,TOP_K:$a,MIN_P:qa,FREQUENCY_PENALTY:Ba,PRESENCE_PENALTY:Ua,REPETITION_PENALTY:Da,SEED:Aa,LOG_PROBS:Va,TOP_LOG_PROBS:za,ECHO:Ha,RESPONSE_FORMAT:Ka,RESPONSE_FORMAT_WITH_SCHEMA:Ya,RESPONSE_SCHEMA:Ja},Wa={type:"range",title:"Dimensions",description:"Select the number of dimensions for the word embedding."},Za={type:"select",title:"Encoding format",description:"Select the encoding format for the word embedding."},ie={DIMENSIONS:Wa,ENCODING_FORMAT:Za};var ge=t=>Object.fromEntries(Object.entries(t).filter(([e,o])=>o!=null));var se=t=>t==null?void 0:t.replace(/\/$/,"");var Xa=Object.defineProperty,vo=Object.getOwnPropertySymbols,Qa=Object.prototype.hasOwnProperty,ei=Object.prototype.propertyIsEnumerable,ti=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Co=(t,e,o)=>e in t?Xa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,O=(t,e)=>{for(var o in e||(e={}))Qa.call(e,o)&&Co(t,o,e[o]);if(vo)for(var o of vo(e))ei.call(e,o)&&Co(t,o,e[o]);return t},z=(t,e,o)=>new Promise((i,s)=>{var r=c=>{try{m(o.next(c));}catch(p){s(p);}},d=c=>{try{m(o.throw(c));}catch(p){s(p);}},m=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,d);m((o=o.apply(t,e)).next());}),oi=function(t,e){this[0]=t,this[1]=e;},ni=(t,e,o)=>{var i=(d,m,c,p)=>{try{var g=o[d](m),f=(m=g.value)instanceof oi,h=g.done;Promise.resolve(f?m[0]:m).then(C=>f?i(d==="return"?d:"next",m[1]?{done:C.done,value:C.value}:C,c,p):c({value:C,done:h})).catch(C=>i("throw",C,c,p));}catch(C){p(C);}},s=d=>r[d]=m=>new Promise((c,p)=>i(d,m,c,p)),r={};return o=o.apply(t,e),r[ti("asyncIterator")]=()=>r,s("next"),s("throw"),s("return"),r},_e=(t,e)=>j({param:"temperature",title:E.TEMPERATURE.title,description:E.TEMPERATURE.description,min:0,max:t,step:.01,default:e}),Ee=t=>j({param:"maxOutputTokens",title:E.MAX_TOKENS.title,description:E.MAX_TOKENS.description,min:0,max:t,step:1,default:0}),Te=t=>ho({param:"stopSequences",title:E.STOP(t).title,description:E.STOP(t).description,max:t}),Me=t=>j({param:"topP",title:E.TOP_P.title,description:E.TOP_P.description,min:0,max:1,step:.01,default:t}),wo=t=>j({param:"topK",title:E.TOP_K.title,description:E.TOP_K.description,min:1,max:40,step:1,default:t}),ko=j({param:"frequencyPenalty",title:E.FREQUENCY_PENALTY.title,description:E.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Io=j({param:"presencePenalty",title:E.PRESENCE_PENALTY.title,description:E.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),jo=j({param:"seed",title:E.SEED.title,description:E.SEED.description,min:0,max:1e6,step:1,default:0}),xe=Mo({param:"toolChoice",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","any","none"]}),ve=yo({param:"safetySettings",title:"Safety settings",description:"The safety rating contains the category of harm and the harm probability level in that category for a piece of content.",objectSchema:zod.z.array(zod.z.object({threshold:zod.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]),category:zod.z.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"])}))}),ai=(t,e,o,i,s)=>zod.z.object({temperature:_e(t,e).schema,maxTokens:Ee(o).schema,stop:Te(i).schema,topP:Me(s).schema,toolChoice:xe.schema,safetySettings:ve.schema}),ii=(t,e,o,i,s)=>({temperature:_e(t,e).def,maxTokens:Ee(o).def,stop:Te(i).def,topP:Me(s).def,toolChoice:xe.def,safetySettings:ve.def}),si=(t,e,o,i,s,r)=>zod.z.object({temperature:_e(t,e).schema,maxTokens:Ee(o).schema,stop:Te(i).schema,topP:Me(s).schema,topK:wo(r).schema,frequencyPenalty:ko.schema,presencePenalty:Io.schema,seed:jo.schema.transform(d=>d===0?void 0:d),toolChoice:xe.schema,safetySettings:ve.schema}),ri=(t,e,o,i,s,r)=>({temperature:_e(t,e).def,maxTokens:Ee(o).def,stop:Te(i).def,topP:Me(s).def,topK:wo(r).def,frequencyPenalty:ko.def,presencePenalty:Io.def,seed:jo.def,toolChoice:xe.def,safetySettings:ve.def}),Ro=t=>j({param:"outputDimensionality",title:ie.DIMENSIONS.title,description:ie.DIMENSIONS.description,min:1,max:t,step:1,default:t}),li=t=>zod.z.object({dimensions:Ro(t).schema}),mi=t=>({dimensions:Ro(t).def}),u={base:(t,e,o,i,s)=>({def:ii(t,e,o,i,s),schema:ai(t,e,o,i,s)}),c1:(t,e,o,i,s,r)=>({def:ri(t,e,o,i,s,r),schema:si(t,e,o,i,s,r)})},be={base:t=>({def:mi(t),schema:li(t)})},S=zod.z.enum([de,I,L,Q]),di="model",ci="function",G={system:I,user:I,assistant:di,tool:ci},J=[_,U,w,A],W=zod.z.enum([_,U,w,A]);zod.z.enum([_]);var No=[_,U],Lo=zod.z.enum([_,U]),Ce=[_,w,A],Oe=zod.z.enum([_,w,A]),pi=zod.z.object({text:zod.z.string()}),ui=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),gi=zod.z.object({candidates:zod.z.array(zod.z.object({content:zod.z.object({role:zod.z.string(),parts:zod.z.array(zod.z.union([pi,ui]))}).optional(),finishReason:zod.z.string(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number()}).optional()}),hi=zod.z.object({text:zod.z.string()}),fi=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),yi=zod.z.object({candidates:zod.z.array(zod.z.object({content:zod.z.object({role:zod.z.string(),parts:zod.z.array(zod.z.union([hi,fi]))}).optional(),finishReason:zod.z.string().optional(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number(),totalTokenCount:zod.z.number()}).optional()}),Fo=zod.z.object({text:zod.z.string().min(1)}),bi=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),_i=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))})}),Ei=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),Ti=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([Fo,bi,_i,Ei]))}),Oo=zod.z.object({parts:zod.z.array(Fo)}),Mi=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),So=zod.z.object({function_calling_config:zod.z.object({mode:zod.z.enum(["ANY","AUTO","NONE"]),allowed_function_names:zod.z.array(zod.z.string()).optional()})}),Go=zod.z.object({stopSequences:zod.z.array(zod.z.string()).optional(),maxOutputTokens:zod.z.number().optional(),temperature:zod.z.number().optional(),topP:zod.z.number().optional(),topK:zod.z.number().optional(),presencePenalty:zod.z.number().optional(),frequencyPenalty:zod.z.number().optional(),seed:zod.z.number().optional()}),Po=zod.z.object({category:zod.z.enum(["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:zod.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])}),xi=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(Ti),systemInstruction:Oo.optional(),system_instruction:Oo.optional(),generationConfig:Go.optional(),generation_config:Go.optional(),safetySettings:zod.z.array(Po).optional(),safety_settings:zod.z.array(Po).optional(),tools:zod.z.object({function_declarations:zod.z.array(Mi)}).optional(),toolConfig:So.optional(),tool_config:So.optional()}),vi="google",$o=class{constructor(){this.version="v1",this.name=vi,this.chatModelFactories={[qo]:{model:Si,modelOptions:Oi,modelSchema:Bo},[Uo]:{model:wi,modelOptions:Pi,modelSchema:Ao},[Jo]:{model:Yi,modelOptions:Ki,modelSchema:ke},[Wo]:{model:Zi,modelOptions:Wi,modelSchema:Ie},[Zo]:{model:es,modelOptions:Qi,modelSchema:Xo},[Yo]:{model:zi,modelOptions:Vi,modelSchema:we},[en]:{model:ss,modelOptions:is,modelSchema:Re},[tn]:{model:ms,modelOptions:ls,modelSchema:Ne},[on]:{model:ps,modelOptions:cs,modelSchema:nn},[Qo]:{model:ns,modelOptions:os,modelSchema:je},[Do]:{model:ji,modelOptions:Ii,modelSchema:Se},[Ko]:{model:Ai,modelOptions:Ui,modelSchema:Pe},[zo]:{model:qi,modelOptions:$i,modelSchema:Ho},[Vo]:{model:Li,modelOptions:Ni,modelSchema:Ge}},this.embeddingModelFactories={[ln]:{model:bs,modelOptions:ys,modelSchema:mn},[dn]:{model:Ts,modelOptions:Es,modelSchema:cn}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,e)=>(t[e]=this.chatModelFactories[e].modelSchema,t),{})}chatModel(t){let e=t.modelName;if(!(e in this.chatModelFactories))throw new ae({info:`Google chat model: ${e} not found`,cause:new Error(`Google chat model: ${e} not found, available chat models:
|
|
6
|
+
Message: ${Vn(o)}`),this.name=Je,this.info=e,this.cause=o,this.name=i!=null?i:Je,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(e){return e instanceof Rt}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},de="system",I="user",L="assistant",Y="tool",zn=[de,I,L,Y],We=zod.z.enum(zn),Hn=[L],Kn=zod.z.enum(Hn),U="image",Ze="base64",Yn=["png","jpeg","webp","gif"],Jn=zod.z.object({type:zod.z.literal(Ze),base64:zod.z.string(),media_type:zod.z.enum(Yn)}),Wn="url",Zn=zod.z.object({type:zod.z.literal(Wn),url:zod.z.string()}),Xn=zod.z.discriminatedUnion("type",[Jn,Zn]),Qn=["low","medium","high","auto"],ea=zod.z.enum(Qn),ta=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(U),detail:ea,value:Xn,metadata:t}),_="text",Nt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(_),value:zod.z.string(),metadata:t}),Xe="partial-text",Lt=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Xe),value:zod.z.string(),metadata:t}),w="tool-call",Ft=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(w),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),metadata:t}),Qe="partial-tool-call",$t=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Qe),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),metadata:t}),A="tool-response",oa=(t=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(A),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),metadata:t}),na=[_,U,w,A],qt=zod.z.enum(na),aa=(t=zod.z.undefined(),e=zod.z.undefined(),o=zod.z.undefined(),i=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Nt(t),ta(e),Ft(o),oa(i)]),ia=[Xe,Qe];zod.z.enum(ia);var sa=(t=zod.z.undefined(),e=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Lt(t),$t(e)]);var et=(t=We,e=zod.z.undefined(),o=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),r=zod.z.undefined())=>zod.z.object({role:t,content:zod.z.array(aa(e,o,i,s)),metadata:r}),tt=(t=Kn,e=zod.z.undefined(),o=zod.z.undefined(),i=zod.z.undefined())=>zod.z.object({role:t,partialContent:sa(e,o),metadata:i}),Bt=t=>Nt().parse({modality:_,value:t}),Ut=(t,e,o,i)=>Ft().parse({modality:w,index:t,id:e,name:o,arguments:i});var At=(t,e)=>tt().parse({role:t,partialContent:Lt().parse({modality:Xe,value:e})}),Dt=(t,e,o,i,s)=>tt().parse({role:t,partialContent:$t().parse({modality:Qe,index:e,id:o,name:i,arguments:s})});var ce=(t=zod.z.record(zod.z.string(),zod.z.any()).optional())=>t,ra=["object","array","number","string","boolean","enum"],kt=zod.z.enum(ra),la=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([kt,zod.z.array(zod.z.union([kt,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()}),ma=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(la),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:ma}).optional();var da="function";var ca=zod.z.enum(["object","array","number","string","boolean","null"]),pa=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:ca.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(pa).optional(),required:zod.z.array(zod.z.string()).optional()});var ua=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 ga=zod.z.enum(["function"]),ha=zod.z.object({type:ga,definition:zod.z.object({schema:ua})}),fa=[da];zod.z.enum(fa);var Vt=(t=zod.z.undefined())=>zod.z.discriminatedUnion("type",[ha.extend({metadata:t})]),M="text",zt="token",ya=[M,zt],Ht=zod.z.enum(ya),ba=zod.z.array(zod.z.string().min(1)),_a=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),fe=(t=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(M),metadata:t,requests:ba}),zod.z.object({modality:zod.z.literal(zt),metadata:t,requests:_a})]),pe="float",Ea=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),Ta="base64",Ma=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),It=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(pe),embeddings:zod.z.array(Ea),usage:It.optional()}),zod.z.object({encodingFormat:zod.z.literal(Ta),embeddings:zod.z.array(Ma),usage:It.optional()})]);var Kt=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),jt=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),xa=jt.extend({topLogProbs:zod.z.array(jt)}),Yt=zod.z.array(xa);zod.z.object({messages:zod.z.array(et()),usage:Kt.optional(),logProbs:Yt.optional()});zod.z.object({partialMessages:zod.z.array(tt()),usage:Kt.optional(),logProbs:Yt.optional()});var va=Object.defineProperty,Jt=Object.getOwnPropertySymbols,Ca=Object.prototype.hasOwnProperty,Oa=Object.prototype.propertyIsEnumerable,Wt=(t,e,o)=>e in t?va(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,ue=(t,e)=>{for(var o in e||(e={}))Ca.call(e,o)&&Wt(t,o,e[o]);if(Jt)for(var o of Jt(e))Oa.call(e,o)&&Wt(t,o,e[o]);return t},Zt="ProviderError",ae=class io extends B{constructor({info:e,cause:o}){super({info:e,cause:o},Zt),this.name=Zt,this.info=e,this.cause=o;}static isProviderError(e){return e instanceof io}},Xt="ModelError",ye=class so extends B{constructor({info:e,cause:o}){super({info:e,cause:o},Xt),this.name=Xt,this.info=e,this.cause=o;}static isModelError(e){return e instanceof so}},Qt="ModelResponseError",D=class ro extends B{constructor({info:e,cause:o}){super({info:e,cause:o},Qt),this.name=Qt,this.cause=o,this.info=e;}static isModelResponseError(e){return e instanceof ro}},eo="InvalidModelRequestError",V=class lo extends B{constructor({info:e,cause:o}){super({info:e,cause:o},eo),this.name=eo,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(e){return e instanceof lo}},to="InvalidConfigError",F=class mo extends B{constructor({info:e,cause:o}){super({info:e,cause:o},to),this.name=to,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(e){return e instanceof mo}},oo="InvalidMessagesError",T=class co extends B{constructor({info:e,cause:o}){super({info:e,cause:o},oo),this.name=oo,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(e){return e instanceof co}},no="InvalidToolsError",ot=class po extends B{constructor({info:e,cause:o}){super({info:e,cause:o},no),this.name=no,this.cause=o,this.info=e,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(e){return e instanceof po}},ao="InvalidEmbeddingRequestsError",J=class uo extends B{constructor({info:e,cause:o}){super({info:e,cause:o},ao),this.name=ao,this.info=e,this.cause=o,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(e){return e instanceof uo}},nt="multi-string",go=zod.z.object({type:zod.z.literal(nt),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()}),Sa=t=>zod.z.array(zod.z.string()).max(t).default([]).optional(),ho=t=>({def:go.parse(ue({type:nt},t)),schema:Sa(t.max)}),at="object-schema",fo=zod.z.object({type:zod.z.literal(at),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),objectSchema:zod.z.any()}),Ga=t=>t.optional(),yo=t=>({def:fo.parse(ue({type:at},t)),schema:Ga(t.objectSchema)}),it="range",bo=zod.z.object({type:zod.z.literal(it),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()}),Pa=(t,e,o,i)=>zod.z.number().min(t).max(e).step(o).default(i).optional(),j=t=>({def:bo.parse(ue({type:it},t)),schema:Pa(t.min,t.max,t.step,t.default)}),st="select-boolean",_o=zod.z.object({type:zod.z.literal(st),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()}),wa=t=>zod.z.boolean().nullable().default(t).optional(),Eo=t=>({def:_o.parse(ue({type:st},t)),schema:wa(t.default)}),rt="select-string",To=zod.z.object({type:zod.z.literal(rt),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))}),ka=(t,e)=>zod.z.enum(e).nullable().default(t).optional(),Mo=t=>({def:To.parse(ue({type:rt},t)),schema:ka(t.default,t.choices)}),Ia=[it,nt,rt,at,st];zod.z.enum(Ia);var xo=zod.z.discriminatedUnion("type",[bo,go,To,_o,fo]),x=(t=We,e=qt)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(t,zod.z.string().min(1).optional()),modalities:zod.z.array(e).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),xo),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(o=>{var i,s;let r=Object.keys(o.def),d=Object.keys((s=(i=o.schema)==null?void 0:i.shape)!=null?s:{});return r.every(m=>d.includes(m))&&d.every(m=>r.includes(m))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"})}),R=(t=Ht)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),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),xo),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(e=>{var o,i;let s=Object.keys(e.def),r=Object.keys((i=(o=e.schema)==null?void 0:o.shape)!=null?i:{});return s.every(d=>r.includes(d))&&r.every(d=>s.includes(d))},{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 ja={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."},Ra={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."},Na=t=>({type:"multi",title:"Stop sequence",description:`Enter up to ${t} sequences that will halt additional text output. The generated text will exclude these sequences.`}),La={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."},Fa={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."},$a={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."},qa={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."},Ba={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."},Ua={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."},Aa={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."},Da={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."},Va={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."},za={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."},Ha={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},Ka={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."},Ya={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."},Ja={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."},E={TEMPERATURE:ja,MAX_TOKENS:Ra,STOP:Na,TOP_A:La,TOP_P:Fa,TOP_K:$a,MIN_P:qa,FREQUENCY_PENALTY:Ba,PRESENCE_PENALTY:Ua,REPETITION_PENALTY:Da,SEED:Aa,LOG_PROBS:Va,TOP_LOG_PROBS:za,ECHO:Ha,RESPONSE_FORMAT:Ka,RESPONSE_FORMAT_WITH_SCHEMA:Ya,RESPONSE_SCHEMA:Ja},Wa={type:"range",title:"Dimensions",description:"Select the number of dimensions for the word embedding."},Za={type:"select",title:"Encoding format",description:"Select the encoding format for the word embedding."},ie={DIMENSIONS:Wa,ENCODING_FORMAT:Za};var ge=t=>Object.fromEntries(Object.entries(t).filter(([e,o])=>o!=null));var se=t=>t==null?void 0:t.replace(/\/$/,"");var Xa=Object.defineProperty,vo=Object.getOwnPropertySymbols,Qa=Object.prototype.hasOwnProperty,ei=Object.prototype.propertyIsEnumerable,ti=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Co=(t,e,o)=>e in t?Xa(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o,O=(t,e)=>{for(var o in e||(e={}))Qa.call(e,o)&&Co(t,o,e[o]);if(vo)for(var o of vo(e))ei.call(e,o)&&Co(t,o,e[o]);return t},z=(t,e,o)=>new Promise((i,s)=>{var r=c=>{try{m(o.next(c));}catch(p){s(p);}},d=c=>{try{m(o.throw(c));}catch(p){s(p);}},m=c=>c.done?i(c.value):Promise.resolve(c.value).then(r,d);m((o=o.apply(t,e)).next());}),oi=function(t,e){this[0]=t,this[1]=e;},ni=(t,e,o)=>{var i=(d,m,c,p)=>{try{var g=o[d](m),f=(m=g.value)instanceof oi,h=g.done;Promise.resolve(f?m[0]:m).then(C=>f?i(d==="return"?d:"next",m[1]?{done:C.done,value:C.value}:C,c,p):c({value:C,done:h})).catch(C=>i("throw",C,c,p));}catch(C){p(C);}},s=d=>r[d]=m=>new Promise((c,p)=>i(d,m,c,p)),r={};return o=o.apply(t,e),r[ti("asyncIterator")]=()=>r,s("next"),s("throw"),s("return"),r},_e=(t,e)=>j({param:"temperature",title:E.TEMPERATURE.title,description:E.TEMPERATURE.description,min:0,max:t,step:.01,default:e}),Ee=t=>j({param:"maxOutputTokens",title:E.MAX_TOKENS.title,description:E.MAX_TOKENS.description,min:0,max:t,step:1,default:0}),Te=t=>ho({param:"stopSequences",title:E.STOP(t).title,description:E.STOP(t).description,max:t}),Me=t=>j({param:"topP",title:E.TOP_P.title,description:E.TOP_P.description,min:0,max:1,step:.01,default:t}),wo=t=>j({param:"topK",title:E.TOP_K.title,description:E.TOP_K.description,min:1,max:40,step:1,default:t}),ko=j({param:"frequencyPenalty",title:E.FREQUENCY_PENALTY.title,description:E.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),Io=j({param:"presencePenalty",title:E.PRESENCE_PENALTY.title,description:E.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),jo=j({param:"seed",title:E.SEED.title,description:E.SEED.description,min:0,max:1e6,step:1,default:0}),xe=Mo({param:"toolChoice",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","any","none"]}),ve=yo({param:"safetySettings",title:"Safety settings",description:"The safety rating contains the category of harm and the harm probability level in that category for a piece of content.",objectSchema:zod.z.array(zod.z.object({threshold:zod.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]),category:zod.z.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"])}))}),ai=(t,e,o,i,s)=>zod.z.object({temperature:_e(t,e).schema,maxTokens:Ee(o).schema,stop:Te(i).schema,topP:Me(s).schema,toolChoice:xe.schema,safetySettings:ve.schema}),ii=(t,e,o,i,s)=>({temperature:_e(t,e).def,maxTokens:Ee(o).def,stop:Te(i).def,topP:Me(s).def,toolChoice:xe.def,safetySettings:ve.def}),si=(t,e,o,i,s,r)=>zod.z.object({temperature:_e(t,e).schema,maxTokens:Ee(o).schema,stop:Te(i).schema,topP:Me(s).schema,topK:wo(r).schema,frequencyPenalty:ko.schema,presencePenalty:Io.schema,seed:jo.schema.transform(d=>d===0?void 0:d),toolChoice:xe.schema,safetySettings:ve.schema}),ri=(t,e,o,i,s,r)=>({temperature:_e(t,e).def,maxTokens:Ee(o).def,stop:Te(i).def,topP:Me(s).def,topK:wo(r).def,frequencyPenalty:ko.def,presencePenalty:Io.def,seed:jo.def,toolChoice:xe.def,safetySettings:ve.def}),Ro=t=>j({param:"outputDimensionality",title:ie.DIMENSIONS.title,description:ie.DIMENSIONS.description,min:1,max:t,step:1,default:t}),li=t=>zod.z.object({dimensions:Ro(t).schema}),mi=t=>({dimensions:Ro(t).def}),u={base:(t,e,o,i,s)=>({def:ii(t,e,o,i,s),schema:ai(t,e,o,i,s)}),c1:(t,e,o,i,s,r)=>({def:ri(t,e,o,i,s,r),schema:si(t,e,o,i,s,r)})},be={base:t=>({def:mi(t),schema:li(t)})},S=zod.z.enum([de,I,L,Y]),di="model",ci="function",G={system:I,user:I,assistant:di,tool:ci},W=[_,U,w,A],Z=zod.z.enum([_,U,w,A]);zod.z.enum([_]);var No=[_,U],Lo=zod.z.enum([_,U]),Ce=[_,w,A],Oe=zod.z.enum([_,w,A]),pi=zod.z.object({text:zod.z.string()}),ui=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),gi=zod.z.object({candidates:zod.z.array(zod.z.object({content:zod.z.object({role:zod.z.string(),parts:zod.z.array(zod.z.union([pi,ui]))}).optional(),finishReason:zod.z.string(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number()}).optional()}),hi=zod.z.object({text:zod.z.string()}),fi=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),yi=zod.z.object({candidates:zod.z.array(zod.z.object({content:zod.z.object({role:zod.z.string(),parts:zod.z.array(zod.z.union([hi,fi]))}).optional(),finishReason:zod.z.string().optional(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number(),totalTokenCount:zod.z.number()}).optional()}),Fo=zod.z.object({text:zod.z.string().min(1)}),bi=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),_i=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))})}),Ei=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),Ti=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([Fo,bi,_i,Ei]))}),Oo=zod.z.object({parts:zod.z.array(Fo)}),Mi=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),So=zod.z.object({function_calling_config:zod.z.object({mode:zod.z.enum(["ANY","AUTO","NONE"]),allowed_function_names:zod.z.array(zod.z.string()).optional()})}),Go=zod.z.object({stopSequences:zod.z.array(zod.z.string()).optional(),maxOutputTokens:zod.z.number().optional(),temperature:zod.z.number().optional(),topP:zod.z.number().optional(),topK:zod.z.number().optional(),presencePenalty:zod.z.number().optional(),frequencyPenalty:zod.z.number().optional(),seed:zod.z.number().optional()}),Po=zod.z.object({category:zod.z.enum(["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:zod.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])}),xi=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(Ti),systemInstruction:Oo.optional(),system_instruction:Oo.optional(),generationConfig:Go.optional(),generation_config:Go.optional(),safetySettings:zod.z.array(Po).optional(),safety_settings:zod.z.array(Po).optional(),tools:zod.z.object({function_declarations:zod.z.array(Mi)}).optional(),toolConfig:So.optional(),tool_config:So.optional()}),vi="google",$o=class{constructor(){this.version="v1",this.name=vi,this.chatModelFactories={[qo]:{model:Si,modelOptions:Oi,modelSchema:Bo},[Uo]:{model:wi,modelOptions:Pi,modelSchema:Ao},[Jo]:{model:Yi,modelOptions:Ki,modelSchema:ke},[Wo]:{model:Zi,modelOptions:Wi,modelSchema:Ie},[Zo]:{model:es,modelOptions:Qi,modelSchema:Xo},[Yo]:{model:zi,modelOptions:Vi,modelSchema:we},[en]:{model:ss,modelOptions:is,modelSchema:Re},[tn]:{model:ms,modelOptions:ls,modelSchema:Ne},[on]:{model:ps,modelOptions:cs,modelSchema:nn},[Qo]:{model:ns,modelOptions:os,modelSchema:je},[Do]:{model:ji,modelOptions:Ii,modelSchema:Se},[Ko]:{model:Ai,modelOptions:Ui,modelSchema:Pe},[zo]:{model:qi,modelOptions:$i,modelSchema:Ho},[Vo]:{model:Li,modelOptions:Ni,modelSchema:Ge}},this.embeddingModelFactories={[ln]:{model:bs,modelOptions:ys,modelSchema:mn},[dn]:{model:Ts,modelOptions:Es,modelSchema:cn}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,e)=>(t[e]=this.chatModelFactories[e].modelSchema,t),{})}chatModel(t){let e=t.modelName;if(!(e in this.chatModelFactories))throw new ae({info:`Google chat model: ${e} not found`,cause:new Error(`Google chat model: ${e} not found, available chat models:
|
|
7
7
|
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[e].model,i=this.chatModelFactories[e].modelOptions.parse(t);return new o(i)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,e)=>(t[e]=this.embeddingModelFactories[e].modelSchema,t),{})}embeddingModel(t){let e=t.modelName;if(!(e in this.embeddingModelFactories))throw new ae({info:`Google embedding model: ${e} not found`,cause:new Error(`Google embedding model: ${e} not found, available embedding models:
|
|
8
|
-
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[e].model,i=this.embeddingModelFactories[e].modelOptions.parse(t);return new o(i)}};$o.baseUrl="https://generativelanguage.googleapis.com/v1beta";var v=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional()}),N=class{constructor(t,e){this.version="v1";var o;let i=v.parse(e);this.modelSchema=t,this.modelName=i.modelName,this.apiKey=i.apiKey,this.baseUrl=se((o=i.baseUrl)!=null?o:$o.baseUrl),this.completeChatUrl=se(i.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=se(i.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(t){return {shouldRetry:!1,delayMs:0}}getTokenCount(t){return t.reduce((e,o)=>e+o.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformModelRequest(t){let e=xi.safeParse(t);if(!e.success)throw new V({info:"Invalid model request",cause:e.error});let o=e.data,i=o.model;if(o.system_instruction&&o.systemInstruction)throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'system_instruction' and 'systemInstruction' are not allowed at the same time")});if(o.generation_config&&o.generationConfig)throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'generation_config' and 'generationConfig' are not allowed at the same time")});if(o.tool_config&&o.toolConfig)throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let s=o.system_instruction||o.systemInstruction,r=o.generation_config||o.generationConfig,d=o.safety_settings||o.safetySettings,m=o.tool_config||o.toolConfig;if(m&&(!o.tools||o.tools.function_declarations.length===0))throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let c={};m&&(m.function_calling_config.mode==="ANY"&&m.function_calling_config.allowed_function_names&&m.function_calling_config.allowed_function_names.length===1?c.toolChoice=m.function_calling_config.allowed_function_names[0]:c.toolChoice=m.function_calling_config.mode.toLowerCase()),c.seed=r==null?void 0:r.seed,c.maxTokens=r==null?void 0:r.maxOutputTokens,c.temperature=r==null?void 0:r.temperature,c.topP=r==null?void 0:r.topP,c.presencePenalty=r==null?void 0:r.presencePenalty,c.frequencyPenalty=r==null?void 0:r.frequencyPenalty,c.stop=r==null?void 0:r.stopSequences,c.safetySettings=d;let p=ce().parse(ge(c)),g=[];s&&s.parts.forEach(h=>{g.push({role:de,content:[{modality:_,value:h.text}]});}),o.contents.forEach(h=>{let C=h.role;switch(C){case"user":{let le=h.parts.map(P=>"text"in P?{modality:_,value:P.text}:{modality:U,detail:"auto",value:{type:Ze,base64:P.inline_data.data,media_type:P.inline_data.mime_type.split("/")[1]}});g.push({role:C,content:le});}break;case"model":{let le=h.parts.map((P,me)=>"text"in P?{modality:_,value:P.text}:{modality:w,id:me.toString(),index:me,name:P.function_call.name,arguments:JSON.stringify(P.function_call.args)});g.push({role:L,content:le});}break;case"function":{let le=h.parts.map((P,me)=>({modality:A,id:me.toString(),index:me,name:P.function_response.name,data:JSON.stringify(P.function_response.response)}));g.push({role:
|
|
8
|
+
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[e].model,i=this.embeddingModelFactories[e].modelOptions.parse(t);return new o(i)}};$o.baseUrl="https://generativelanguage.googleapis.com/v1beta";var v=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),completeChatUrl:zod.z.string().url().optional(),streamChatUrl:zod.z.string().url().optional()}),N=class{constructor(t,e){this.version="v1";var o;let i=v.parse(e);this.modelSchema=t,this.modelName=i.modelName,this.apiKey=i.apiKey,this.baseUrl=se((o=i.baseUrl)!=null?o:$o.baseUrl),this.completeChatUrl=se(i.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=se(i.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(t){return {shouldRetry:!1,delayMs:0}}getTokenCount(t){return t.reduce((e,o)=>e+o.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformModelRequest(t){let e=xi.safeParse(t);if(!e.success)throw new V({info:"Invalid model request",cause:e.error});let o=e.data,i=o.model;if(o.system_instruction&&o.systemInstruction)throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'system_instruction' and 'systemInstruction' are not allowed at the same time")});if(o.generation_config&&o.generationConfig)throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'generation_config' and 'generationConfig' are not allowed at the same time")});if(o.tool_config&&o.toolConfig)throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let s=o.system_instruction||o.systemInstruction,r=o.generation_config||o.generationConfig,d=o.safety_settings||o.safetySettings,m=o.tool_config||o.toolConfig;if(m&&(!o.tools||o.tools.function_declarations.length===0))throw new V({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let c={};m&&(m.function_calling_config.mode==="ANY"&&m.function_calling_config.allowed_function_names&&m.function_calling_config.allowed_function_names.length===1?c.toolChoice=m.function_calling_config.allowed_function_names[0]:c.toolChoice=m.function_calling_config.mode.toLowerCase()),c.seed=r==null?void 0:r.seed,c.maxTokens=r==null?void 0:r.maxOutputTokens,c.temperature=r==null?void 0:r.temperature,c.topP=r==null?void 0:r.topP,c.presencePenalty=r==null?void 0:r.presencePenalty,c.frequencyPenalty=r==null?void 0:r.frequencyPenalty,c.stop=r==null?void 0:r.stopSequences,c.safetySettings=d;let p=ce().parse(ge(c)),g=[];s&&s.parts.forEach(h=>{g.push({role:de,content:[{modality:_,value:h.text}]});}),o.contents.forEach(h=>{let C=h.role;switch(C){case"user":{let le=h.parts.map(P=>"text"in P?{modality:_,value:P.text}:{modality:U,detail:"auto",value:{type:Ze,base64:P.inline_data.data,media_type:P.inline_data.mime_type.split("/")[1]}});g.push({role:C,content:le});}break;case"model":{let le=h.parts.map((P,me)=>"text"in P?{modality:_,value:P.text}:{modality:w,id:me.toString(),index:me,name:P.function_call.name,arguments:JSON.stringify(P.function_call.args)});g.push({role:L,content:le});}break;case"function":{let le=h.parts.map((P,me)=>({modality:A,id:me.toString(),index:me,name:P.function_response.name,data:JSON.stringify(P.function_response.response)}));g.push({role:Y,content:le});}break;default:throw new T({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${h.role}' is not supported for model : ${this.modelName}`)})}});let f=[];return o.tools&&o.tools.function_declarations.forEach(h=>{f.push({type:"function",definition:{schema:{name:h.name,description:h.description,parameters:h.parameters}}});}),{modelName:i,config:p,messages:g,tools:f.length>0?f:void 0}}transformConfig(t,e,o){let i=t.toolChoice;delete t.toolChoice;let s=this.modelSchema.config.schema.safeParse(t);if(!s.success)throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:s.error});let r=s.data;Object.keys(r).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${p}',
|
|
9
9
|
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let d=Object.keys(r).reduce((p,g)=>{let f=this.modelSchema.config.def[g],h=f.param,C=r[g];return h==="maxOutputTokens"&&f.type==="range"&&C===0?p[h]=f.max:p[h]=C,p},{}),m=d.safetySettings;delete d.safetySettings;let c;if(i!==void 0){let p=i;if(!o||o&&o.length===0)throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let g=this.modelSchema.config.def.toolChoice;if(g.choices.includes(p))p==="any"?c={function_calling_config:{mode:"ANY",allowed_function_names:o.map(f=>f.definition.schema.name)}}:c={function_calling_config:{mode:p.toUpperCase()}};else if(o.map(f=>f.definition.schema.name).includes(p))c={function_calling_config:{mode:"ANY",allowed_function_names:[p]}};else throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${p}' is not part of provided 'tools' names or
|
|
10
10
|
one of [${g.choices.join(", ")}]`)})}}return O(O({generation_config:d},c?{tool_config:c}:{}),m?{safety_settings:m}:{})}transformMessages(t){if(!t||t&&t.length===0)return {messages:[]};let e=t.map(r=>{let d=et().safeParse(r);if(!d.success)throw new T({info:"Invalid messages",cause:d.error});return d.data});e.forEach(r=>{r.content.forEach(d=>{if(!this.modelSchema.modalities.includes(d.modality))throw new T({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${d.modality}',
|
|
11
11
|
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),e.forEach(r=>{if(!Object.keys(this.modelSchema.roles).includes(r.role))throw new T({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${r.role}',
|
|
12
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let o={parts:[]},i=[];if(e.forEach(r=>{switch(r.role){case de:r.content.forEach(d=>{if(d.modality===_)o.parts.push({text:d.value});else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${d.modality}'`)})});break;case L:{let d=[];r.content.forEach(m=>{if(m.modality===_)d.push({text:m.value});else if(m.modality===w)d.push({function_call:{name:m.name,args:JSON.parse(m.arguments)}});else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${m.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:d});}break;case I:{let d=[];r.content.forEach(m=>{if(m.modality===_)d.push({text:m.value});else if(m.modality===U){if(m.value.type==="base64")d.push({inline_data:{mime_type:m.value.media_type,data:m.value.base64}});else if(m.value.type==="url")throw new T({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${m.value.type}'`)})}else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${m.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:d});}break;case
|
|
13
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),i[0].role!==this.modelSchema.roles[I])throw new T({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});let s=r=>r===this.modelSchema.roles[I]||r===this.modelSchema.roles[Q]?[this.modelSchema.roles[L]]:[this.modelSchema.roles[I],this.modelSchema.roles[Q]];for(let r=1;r<i.length;r++)if(!s(i[r-1].role).includes(i[r].role))throw new T({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${i[r].role}' after message with role : '${i[r-1].role}'`)});if(i[i.length-1].role!==this.modelSchema.roles[I])throw new T({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires last message to be from user`)});return O({contents:i},o.parts.length>0?{system_instruction:o}:{})}transformTools(t){if(!this.modelSchema.modalities.includes(w))throw new ot({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${w}'`)});return !t||t&&t.length===0?{tools:[]}:{tools:t.map(e=>{let o=Vt().safeParse(e);if(!o.success)throw new ot({info:"Invalid tools",cause:o.error});return o.data}).map(e=>({function_declarations:[{name:e.definition.schema.name,description:e.definition.schema.description,parameters:e.definition.schema.parameters}]}))}}getCompleteChatUrl(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getCompleteChatHeaders(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getCompleteChatData(t,e,o){return z(this,null,function*(){let i=this.transformConfig(t,e,o),s=this.transformMessages(e);if(s.messages&&s.messages.length===0)throw new T({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return new Promise(d=>{d(O(O(O(O({},this.getDefaultParams()),i),s),r));})})}transformCompleteChatResponse(t){let e=gi.safeParse(t);if(e.success){if(e.data.candidates.length===0)throw new D({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(e.data)}`)});let o=e.data,i=[],s,r=o.candidates[0].content;if(r){let m=r.parts.map((c,p)=>{if("text"in c&&c.text!==void 0)return Bt(c.text);if("functionCall"in c&&c.functionCall!==void 0)return Ut(p,`${c.functionCall.name}_${p}`,c.functionCall.name,JSON.stringify(c.functionCall.args))});return i.push({role:L,content:m}),o.usageMetadata&&(s={promptTokens:o.usageMetadata.promptTokenCount,totalTokens:o.usageMetadata.totalTokenCount,completionTokens:o.usageMetadata.candidatesTokenCount||0}),{messages:i,usage:s,logProbs:void 0}}let d=o.candidates[0].safetyRatings;if(d&&d.length>0&&d.forEach(m=>{if(m.blocked)throw new D({info:`Blocked content for category: ${m.category} with probability: ${m.probability}`,cause:new Error(`Blocked content for category: ${m.category} with probability: ${m.probability}`)})}),o.candidates[0].finishReason==="SAFETY")throw new D({info:"Blocked content, model response finished with safety reason",cause:new Error("Blocked content, model response finished with safety reason")})}throw new D({info:"Invalid response from model",cause:e.error})}getStreamChatUrl(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.streamChatUrl);})})}getStreamChatHeaders(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getStreamChatData(t,e,o){return z(this,null,function*(){let i=this.transformConfig(t,e,o),s=this.transformMessages(e);if(s.messages&&s.messages.length===0)throw new T({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return new Promise(d=>{d(O(O(O(O({},this.getDefaultParams()),i),s),r));})})}transformStreamChatResponseChunk(t,e){return ni(this,null,function*(){let o=(e+t).split(",\r").filter(i=>i.trim()!=="");for(let i of o){let s=i;if(s=s.replace(/\n/g,""),s.startsWith("["))s=s.slice(1);else if(s.endsWith("]")){if(s==="]")return;s=s.slice(0,-1);}let r;try{r=JSON.parse(s);}catch(m){if(m instanceof SyntaxError){e=s;continue}else throw m}e="";let d=yi.safeParse(r);if(d.success){let m={partialMessages:[]},c=d.data;if(c.candidates.length>0){let p=c.candidates[0].content;p&&"parts"in p&&p.parts.length>0&&p.parts.forEach((g,f)=>{if("text"in g&&g.text!==void 0&&m.partialMessages.push(At(L,g.text)),"functionCall"in g&&g.functionCall!==void 0){let h=g.functionCall;m.partialMessages.push(Dt(L,f,`${h.name}_${f}`,h.name,JSON.stringify(h.args)));}});}c.usageMetadata&&(m.usage={promptTokens:c.usageMetadata.promptTokenCount,completionTokens:c.usageMetadata.candidatesTokenCount,totalTokens:c.usageMetadata.totalTokenCount}),yield {partialResponse:m,buffer:e};}else throw new D({info:"Invalid response from model",cause:d.error})}yield {partialResponse:{partialMessages:[]},buffer:e};})}},re=class extends N{transformMessages(t){let e=super.transformMessages(t);if(e.systemInstruction){let o={role:this.modelSchema.roles[I],parts:e.systemInstruction.parts};e.contents.unshift(o),delete e.systemInstruction;}return e}},qo="gemini-pro",Ci="A model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Bo=x(S,Oe).parse({name:qo,description:Ci,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),Oi=v,Si=class extends re{constructor(t){super(Bo,t);}},Uo="gemini-pro-vision",Gi="An image understanding model to handle a broad range of applications",Ao=x(S,Lo).parse({name:Uo,description:Gi,maxInputTokens:12288,maxOutputTokens:4096,roles:G,modalities:No,config:{def:u.c1(1,.4,4096,4,1,32).def,schema:u.c1(1,.4,4096,4,1,32).schema}}),Pi=v,wi=class extends re{constructor(t){super(Ao,t);}},Do="gemini-1.0-pro",ki="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Se=x(S,Oe).parse({name:Do,description:ki,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),Ii=v,ji=class extends re{constructor(t){super(Se,t);}},Vo="gemini-1.0-pro-001",Ri="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Ge=x(S,Oe).parse({name:Vo,description:Ri,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),Ni=v,Li=class extends re{constructor(t){super(Ge,t);}},zo="gemini-1.0-pro-latest",Fi="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for natural language tasks, multi-turn text and code chat, and code generation",Ho=x(S,Oe).parse({name:zo,description:Fi,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),$i=v,qi=class extends re{constructor(t){super(Ho,t);}},Ko="gemini-1.0-pro-vision",Bi="Google's predecessor to Gemini 1.5 Pro, an image understanding model to handle a broad range of applications",Pe=x(S,Lo).parse({name:Ko,description:Bi,maxInputTokens:12288,maxOutputTokens:4096,roles:G,modalities:No,config:{def:u.c1(1,.4,4096,4,1,32).def,schema:u.c1(1,.4,4096,4,1,32).schema}}),Ui=v,Ai=class extends re{constructor(t){super(Pe,t);}},Yo="gemini-1.5-flash",Di="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",we=x(S,W).parse({name:Yo,description:Di,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),Vi=v,zi=class extends N{constructor(t){super(we,t);}},Jo="gemini-1.5-flash-001",Hi="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",ke=x(S,W).parse({name:Jo,description:Hi,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),Ki=v,Yi=class extends N{constructor(t){super(ke,t);}},Wo="gemini-1.5-flash-002",Ji="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Ie=x(S,W).parse({name:Wo,description:Ji,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,40).def,schema:u.c1(2,1,8192,4,.95,40).schema}}),Wi=v,Zi=class extends N{constructor(t){super(Ie,t);}},Zo="gemini-1.5-flash-latest",Xi="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Xo=x(S,W).parse({name:Zo,description:Xi,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),Qi=v,es=class extends N{constructor(t){super(Xo,t);}},Qo="gemini-1.5-pro",ts="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",je=x(S,W).parse({name:Qo,description:ts,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),os=v,ns=class extends N{constructor(t){super(je,t);}},en="gemini-1.5-pro-001",as="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Re=x(S,W).parse({name:en,description:as,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),is=v,ss=class extends N{constructor(t){super(Re,t);}},tn="gemini-1.5-pro-002",rs="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Ne=x(S,W).parse({name:tn,description:rs,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,40).def,schema:u.c1(2,1,8192,4,.95,40).schema}}),ls=v,ms=class extends N{constructor(t){super(Ne,t);}},on="gemini-1.5-pro-latest",ds="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",nn=x(S,W).parse({name:on,description:ds,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:J,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),cs=v,ps=class extends N{constructor(t){super(nn,t);}},an=[M],sn=zod.z.enum([M]),us=zod.z.object({embeddings:zod.z.array(zod.z.object({values:zod.z.array(zod.z.number())}))}),gs=zod.z.object({model:zod.z.string().min(1),content:zod.z.object({parts:zod.z.array(zod.z.object({text:zod.z.string().min(1)})).min(1)})}),hs=zod.z.object({model:zod.z.string().min(1).optional(),requests:zod.z.array(gs).min(1),outputDimensionality:zod.z.number().int().min(1).optional()}),lt=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url(),getEmbeddingsUrl:zod.z.string().url().optional()}),rn=class{constructor(t,e){this.version="v1";let o=lt.parse(e);this.modelSchema=t,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=se(o.baseUrl),this.getEmbeddingsUrl=se(o.getEmbeddingsUrl||`${this.baseUrl}/models/${this.modelName}:batchEmbedContents?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelName}}getRetryDelay(t){return {shouldRetry:!1,delayMs:0}}getTokenCount(t){return t.requests.reduce((e,o)=>e+o.length,0)}transformModelRequest(t){let e=hs.safeParse(t);if(!e.success)throw new V({info:"Invalid model request",cause:e.error});let o=e.data,i=o.model,s={outputDimensionality:o.outputDimensionality},r=ce().parse(ge(s)),d={modality:M,requests:o.requests.reduce((m,c)=>(m.push(...c.content.parts.map(p=>p.text)),m),[])};return {modelName:i,config:r,embeddingRequests:d}}transformConfig(t,e){let o=this.modelSchema.config.schema.safeParse(t);if(!o.success)throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:o.error});let i=o.data;return Object.keys(i).forEach(s=>{if(!this.modelSchema.config.def[s])throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${s}',
|
|
14
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(i).reduce((s,r)=>{let d=this.modelSchema.config.def[r].param,m=i[r];return s[d]=m,s},{})}transformEmbeddingRequests(t){let e=fe().safeParse(t);if(!e.success)throw new
|
|
12
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let o={parts:[]},i=[];if(e.forEach(r=>{switch(r.role){case de:r.content.forEach(d=>{if(d.modality===_)o.parts.push({text:d.value});else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${d.modality}'`)})});break;case L:{let d=[];r.content.forEach(m=>{if(m.modality===_)d.push({text:m.value});else if(m.modality===w)d.push({function_call:{name:m.name,args:JSON.parse(m.arguments)}});else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${m.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:d});}break;case I:{let d=[];r.content.forEach(m=>{if(m.modality===_)d.push({text:m.value});else if(m.modality===U){if(m.value.type==="base64")d.push({inline_data:{mime_type:m.value.media_type,data:m.value.base64}});else if(m.value.type==="url")throw new T({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${m.value.type}'`)})}else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${m.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:d});}break;case Y:{let d=[];r.content.forEach(m=>{if(m.modality===A)d.push({function_response:{name:m.name,response:JSON.parse(m.data)}});else throw new T({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${m.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:d});}break;default:throw new T({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' is not supported,
|
|
13
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),i[0].role!==this.modelSchema.roles[I])throw new T({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});let s=r=>r===this.modelSchema.roles[I]||r===this.modelSchema.roles[Y]?[this.modelSchema.roles[L]]:[this.modelSchema.roles[I],this.modelSchema.roles[Y]];for(let r=1;r<i.length;r++)if(!s(i[r-1].role).includes(i[r].role))throw new T({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${i[r].role}' after message with role : '${i[r-1].role}'`)});if(i[i.length-1].role!==this.modelSchema.roles[I]&&i[i.length-1].role!==this.modelSchema.roles[Y])throw new T({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires last message to be from user`)});return O({contents:i},o.parts.length>0?{system_instruction:o}:{})}transformTools(t){if(!this.modelSchema.modalities.includes(w))throw new ot({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${w}'`)});return !t||t&&t.length===0?{tools:[]}:{tools:t.map(e=>{let o=Vt().safeParse(e);if(!o.success)throw new ot({info:"Invalid tools",cause:o.error});return o.data}).map(e=>({function_declarations:[{name:e.definition.schema.name,description:e.definition.schema.description,parameters:e.definition.schema.parameters}]}))}}getCompleteChatUrl(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getCompleteChatHeaders(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getCompleteChatData(t,e,o){return z(this,null,function*(){let i=this.transformConfig(t,e,o),s=this.transformMessages(e);if(s.messages&&s.messages.length===0)throw new T({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return new Promise(d=>{d(O(O(O(O({},this.getDefaultParams()),i),s),r));})})}transformCompleteChatResponse(t){let e=gi.safeParse(t);if(e.success){if(e.data.candidates.length===0)throw new D({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(e.data)}`)});let o=e.data,i=[],s,r=o.candidates[0].content;if(r){let m=r.parts.map((c,p)=>{if("text"in c&&c.text!==void 0)return Bt(c.text);if("functionCall"in c&&c.functionCall!==void 0)return Ut(p,`${c.functionCall.name}_${p}`,c.functionCall.name,JSON.stringify(c.functionCall.args))});return i.push({role:L,content:m}),o.usageMetadata&&(s={promptTokens:o.usageMetadata.promptTokenCount,totalTokens:o.usageMetadata.totalTokenCount,completionTokens:o.usageMetadata.candidatesTokenCount||0}),{messages:i,usage:s,logProbs:void 0}}let d=o.candidates[0].safetyRatings;if(d&&d.length>0&&d.forEach(m=>{if(m.blocked)throw new D({info:`Blocked content for category: ${m.category} with probability: ${m.probability}`,cause:new Error(`Blocked content for category: ${m.category} with probability: ${m.probability}`)})}),o.candidates[0].finishReason==="SAFETY")throw new D({info:"Blocked content, model response finished with safety reason",cause:new Error("Blocked content, model response finished with safety reason")})}throw new D({info:"Invalid response from model",cause:e.error})}getStreamChatUrl(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.streamChatUrl);})})}getStreamChatHeaders(t,e,o){return z(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getStreamChatData(t,e,o){return z(this,null,function*(){let i=this.transformConfig(t,e,o),s=this.transformMessages(e);if(s.messages&&s.messages.length===0)throw new T({info:"Messages are required",cause:new Error("Messages are required")});let r=o?this.transformTools(o):{};return new Promise(d=>{d(O(O(O(O({},this.getDefaultParams()),i),s),r));})})}transformStreamChatResponseChunk(t,e){return ni(this,null,function*(){let o=(e+t).split(",\r").filter(i=>i.trim()!=="");for(let i of o){let s=i;if(s=s.replace(/\n/g,""),s.startsWith("["))s=s.slice(1);else if(s.endsWith("]")){if(s==="]")return;s=s.slice(0,-1);}let r;try{r=JSON.parse(s);}catch(m){if(m instanceof SyntaxError){e=s;continue}else throw m}e="";let d=yi.safeParse(r);if(d.success){let m={partialMessages:[]},c=d.data;if(c.candidates.length>0){let p=c.candidates[0].content;p&&"parts"in p&&p.parts.length>0&&p.parts.forEach((g,f)=>{if("text"in g&&g.text!==void 0&&m.partialMessages.push(At(L,g.text)),"functionCall"in g&&g.functionCall!==void 0){let h=g.functionCall;m.partialMessages.push(Dt(L,f,`${h.name}_${f}`,h.name,JSON.stringify(h.args)));}});}c.usageMetadata&&(m.usage={promptTokens:c.usageMetadata.promptTokenCount,completionTokens:c.usageMetadata.candidatesTokenCount,totalTokens:c.usageMetadata.totalTokenCount}),yield {partialResponse:m,buffer:e};}else throw new D({info:"Invalid response from model",cause:d.error})}yield {partialResponse:{partialMessages:[]},buffer:e};})}},re=class extends N{transformMessages(t){let e=super.transformMessages(t);if(e.systemInstruction){let o={role:this.modelSchema.roles[I],parts:e.systemInstruction.parts};e.contents.unshift(o),delete e.systemInstruction;}return e}},qo="gemini-pro",Ci="A model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Bo=x(S,Oe).parse({name:qo,description:Ci,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),Oi=v,Si=class extends re{constructor(t){super(Bo,t);}},Uo="gemini-pro-vision",Gi="An image understanding model to handle a broad range of applications",Ao=x(S,Lo).parse({name:Uo,description:Gi,maxInputTokens:12288,maxOutputTokens:4096,roles:G,modalities:No,config:{def:u.c1(1,.4,4096,4,1,32).def,schema:u.c1(1,.4,4096,4,1,32).schema}}),Pi=v,wi=class extends re{constructor(t){super(Ao,t);}},Do="gemini-1.0-pro",ki="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Se=x(S,Oe).parse({name:Do,description:ki,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),Ii=v,ji=class extends re{constructor(t){super(Se,t);}},Vo="gemini-1.0-pro-001",Ri="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Ge=x(S,Oe).parse({name:Vo,description:Ri,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),Ni=v,Li=class extends re{constructor(t){super(Ge,t);}},zo="gemini-1.0-pro-latest",Fi="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for natural language tasks, multi-turn text and code chat, and code generation",Ho=x(S,Oe).parse({name:zo,description:Fi,maxInputTokens:30720,maxOutputTokens:2048,roles:G,modalities:Ce,config:{def:u.base(1,.9,2048,4,1).def,schema:u.base(1,.9,2048,4,1).schema}}),$i=v,qi=class extends re{constructor(t){super(Ho,t);}},Ko="gemini-1.0-pro-vision",Bi="Google's predecessor to Gemini 1.5 Pro, an image understanding model to handle a broad range of applications",Pe=x(S,Lo).parse({name:Ko,description:Bi,maxInputTokens:12288,maxOutputTokens:4096,roles:G,modalities:No,config:{def:u.c1(1,.4,4096,4,1,32).def,schema:u.c1(1,.4,4096,4,1,32).schema}}),Ui=v,Ai=class extends re{constructor(t){super(Pe,t);}},Yo="gemini-1.5-flash",Di="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",we=x(S,Z).parse({name:Yo,description:Di,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),Vi=v,zi=class extends N{constructor(t){super(we,t);}},Jo="gemini-1.5-flash-001",Hi="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",ke=x(S,Z).parse({name:Jo,description:Hi,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),Ki=v,Yi=class extends N{constructor(t){super(ke,t);}},Wo="gemini-1.5-flash-002",Ji="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Ie=x(S,Z).parse({name:Wo,description:Ji,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,40).def,schema:u.c1(2,1,8192,4,.95,40).schema}}),Wi=v,Zi=class extends N{constructor(t){super(Ie,t);}},Zo="gemini-1.5-flash-latest",Xi="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Xo=x(S,Z).parse({name:Zo,description:Xi,maxInputTokens:1e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),Qi=v,es=class extends N{constructor(t){super(Xo,t);}},Qo="gemini-1.5-pro",ts="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",je=x(S,Z).parse({name:Qo,description:ts,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),os=v,ns=class extends N{constructor(t){super(je,t);}},en="gemini-1.5-pro-001",as="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Re=x(S,Z).parse({name:en,description:as,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),is=v,ss=class extends N{constructor(t){super(Re,t);}},tn="gemini-1.5-pro-002",rs="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Ne=x(S,Z).parse({name:tn,description:rs,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,40).def,schema:u.c1(2,1,8192,4,.95,40).schema}}),ls=v,ms=class extends N{constructor(t){super(Ne,t);}},on="gemini-1.5-pro-latest",ds="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",nn=x(S,Z).parse({name:on,description:ds,maxInputTokens:2e6,maxOutputTokens:8192,roles:G,modalities:W,config:{def:u.c1(2,1,8192,4,.95,64).def,schema:u.c1(2,1,8192,4,.95,64).schema}}),cs=v,ps=class extends N{constructor(t){super(nn,t);}},an=[M],sn=zod.z.enum([M]),us=zod.z.object({embeddings:zod.z.array(zod.z.object({values:zod.z.array(zod.z.number())}))}),gs=zod.z.object({model:zod.z.string().min(1),content:zod.z.object({parts:zod.z.array(zod.z.object({text:zod.z.string().min(1)})).min(1)})}),hs=zod.z.object({model:zod.z.string().min(1).optional(),requests:zod.z.array(gs).min(1),outputDimensionality:zod.z.number().int().min(1).optional()}),lt=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url(),getEmbeddingsUrl:zod.z.string().url().optional()}),rn=class{constructor(t,e){this.version="v1";let o=lt.parse(e);this.modelSchema=t,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=se(o.baseUrl),this.getEmbeddingsUrl=se(o.getEmbeddingsUrl||`${this.baseUrl}/models/${this.modelName}:batchEmbedContents?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {model:this.modelName}}getRetryDelay(t){return {shouldRetry:!1,delayMs:0}}getTokenCount(t){return t.requests.reduce((e,o)=>e+o.length,0)}transformModelRequest(t){let e=hs.safeParse(t);if(!e.success)throw new V({info:"Invalid model request",cause:e.error});let o=e.data,i=o.model,s={outputDimensionality:o.outputDimensionality},r=ce().parse(ge(s)),d={modality:M,requests:o.requests.reduce((m,c)=>(m.push(...c.content.parts.map(p=>p.text)),m),[])};return {modelName:i,config:r,embeddingRequests:d}}transformConfig(t,e){let o=this.modelSchema.config.schema.safeParse(t);if(!o.success)throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:o.error});let i=o.data;return Object.keys(i).forEach(s=>{if(!this.modelSchema.config.def[s])throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${s}',
|
|
14
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(i).reduce((s,r)=>{let d=this.modelSchema.config.def[r].param,m=i[r];return s[d]=m,s},{})}transformEmbeddingRequests(t){let e=fe().safeParse(t);if(!e.success)throw new J({info:"Invalid embedding requests",cause:e.error});if(t.modality!==M)throw new J({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${M}' modality is supported for model : '${this.modelName}'`)});return {requests:e.data.requests.map(o=>({model:`models/${this.modelName}`,content:{parts:[{text:o}]}}))}}getGetEmbeddingsUrl(t,e){return z(this,null,function*(){return new Promise(o=>{o(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(t,e){return z(this,null,function*(){return new Promise(o=>{o(this.getDefaultHeaders());})})}getGetEmbeddingsData(t,e){return z(this,null,function*(){return new Promise(o=>{let i=this.transformConfig(t),s=this.transformEmbeddingRequests(e);if(e.requests.length===0)throw new J({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});i.outputDimensionality&&(s.requests.forEach(r=>{r.outputDimensionality=i.outputDimensionality;}),delete i.outputDimensionality),o(O(O(O({},this.getDefaultParams()),i),s));})})}transformGetEmbeddingsResponse(t){let e=us.safeParse(t);if(e.success){let o=e.data.embeddings.map((i,s)=>({index:s,embedding:i.values}));return {encodingFormat:pe,embeddings:o}}throw new D({info:"Invalid response from model",cause:e.error})}},ln="text-embedding-001",fs="text-embedding-001",mn=R(sn).parse({name:ln,description:fs,modalities:an,maxInputTokens:2048,maxOutputTokens:768,config:{def:be.base(768).def,schema:be.base(768).schema}}),ys=lt,bs=class extends rn{constructor(t){super(mn,t);}},dn="text-embedding-004",_s="text-embedding-004",cn=R(sn).parse({name:dn,description:_s,modalities:an,maxInputTokens:2048,maxOutputTokens:768,config:{def:be.base(768).def,schema:be.base(768).schema}}),Es=lt,Ts=class extends rn{constructor(t){super(cn,t);}};var Ms="vertex",ee=class{constructor(){this.version="v1";this.name=Ms;this.chatModelFactories={[bn]:{model:qe,modelOptions:_n,modelSchema:pt},[En]:{model:Be,modelOptions:Tn,modelSchema:ut},[Mn]:{model:Ue,modelOptions:xn,modelSchema:gt},[vn]:{model:Ae,modelOptions:Cn,modelSchema:ht},[On]:{model:De,modelOptions:Sn,modelSchema:ft},[Gn]:{model:Ve,modelOptions:Pn,modelSchema:yt},[pn]:{model:Le,modelOptions:un,modelSchema:mt},[fn]:{model:$e,modelOptions:yn,modelSchema:ct},[gn]:{model:Fe,modelOptions:hn,modelSchema:dt}};this.embeddingModelFactories={[bt]:{model:ze,modelOptions:wn,modelSchema:_t},[Et]:{model:He,modelOptions:kn,modelSchema:Tt},[vt]:{model:Ye,modelOptions:jn,modelSchema:Ct},[Mt]:{model:Ke,modelOptions:In,modelSchema:xt}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,o)=>(e[o]=this.chatModelFactories[o].modelSchema,e),{})}chatModel(e){let o=e.modelName;if(!(o in this.chatModelFactories))throw new ae({info:`Vertex chat model: ${o} not found`,cause:new Error(`Vertex chat model: ${o} not found, available chat models:
|
|
15
15
|
${this.chatModelLiterals().join(", ")}`)});let i=this.chatModelFactories[o].model,s=this.chatModelFactories[o].modelOptions.parse(e);return new i(s)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,o)=>(e[o]=this.embeddingModelFactories[o].modelSchema,e),{})}embeddingModel(e){let o=e.modelName;if(!(o in this.embeddingModelFactories))throw new ae({info:`Vertex embedding model: ${o} not found`,cause:new Error(`Vertex embedding model: ${o} not found, available embedding models:
|
|
16
|
-
${this.embeddingModelLiterals().join(", ")}`)});let i=this.embeddingModelFactories[o].model,s=this.embeddingModelFactories[o].modelOptions.parse(e);return new i(s)}};ee.baseUrl=(e,o,i="google")=>`https://${e}-aiplatform.googleapis.com/v1/projects/${o}/locations/${e}/publishers/${i}`;var b=zod.z.object({accessToken:zod.z.string(),modelName:zod.z.string(),baseUrl:zod.z.string().url().optional(),location:zod.z.string().optional(),projectId:zod.z.string().optional(),publisher:zod.z.string().optional()}),y=class extends N{constructor(o,i){let s=b.parse(i),r;if(s.baseUrl)r=s.baseUrl;else if(s.location&&s.projectId)r=ee.baseUrl(s.location,s.projectId,s.publisher);else throw new ye({info:"Either 'baseUrl' must be provided or 'location' and 'projectId' must be provided",cause:new Error("Either 'baseUrl' must be provided or 'location' and 'projectId' must be provided")});super(o,{modelName:s.modelName,apiKey:"random-api-key",completeChatUrl:`${r}/models/${s.modelName}:generateContent`,streamChatUrl:`${r}/models/${s.modelName}:streamGenerateContent`});this.version="v1";this.modelSchema=o,this.modelName=s.modelName,this.accessToken=s.accessToken,this.location=s.location,this.projectId=s.projectId,this.publisher=s.publisher;}getDefaultHeaders(){return wt(ne({},super.getDefaultHeaders()),{Authorization:`Bearer ${this.accessToken}`})}};var pn="gemini-1.0-pro",mt=Se,un=b,Le=class extends y{constructor(e){super(mt,e);}};var gn="gemini-1.0-pro-001",dt=Ge,hn=b,Fe=class extends y{constructor(e){super(dt,e);}};var fn="gemini-1.0-pro-vision",ct=Pe,yn=b,$e=class extends y{constructor(e){super(ct,e);}};var bn="gemini-1.5-flash-001",pt=ke,_n=b,qe=class extends y{constructor(e){super(pt,e);}};var En="gemini-1.5-flash-002",ut=Ie,Tn=b,Be=class extends y{constructor(e){super(ut,e);}};var Mn="gemini-1.5-flash",gt=we,xn=b,Ue=class extends y{constructor(e){super(gt,e);}};var vn="gemini-1.5-pro-001",ht=Re,Cn=b,Ae=class extends y{constructor(e){super(ht,e);}};var On="gemini-1.5-pro-002",ft=Ne,Sn=b,De=class extends y{constructor(e){super(ft,e);}};var Gn="gemini-1.5-pro",yt=je,Pn=b,Ve=class extends y{constructor(e){super(yt,e);}};var
|
|
17
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),{parameters:Object.keys(s).reduce((d,m)=>{let p=this.modelSchema.config.def[m].param,g=s[m];return d[p]=g,d},{})}}transformEmbeddingRequests(e){let o=fe().safeParse(e);if(!o.success)throw new
|
|
16
|
+
${this.embeddingModelLiterals().join(", ")}`)});let i=this.embeddingModelFactories[o].model,s=this.embeddingModelFactories[o].modelOptions.parse(e);return new i(s)}};ee.baseUrl=(e,o,i="google")=>`https://${e}-aiplatform.googleapis.com/v1/projects/${o}/locations/${e}/publishers/${i}`;var b=zod.z.object({accessToken:zod.z.string(),modelName:zod.z.string(),baseUrl:zod.z.string().url().optional(),location:zod.z.string().optional(),projectId:zod.z.string().optional(),publisher:zod.z.string().optional()}),y=class extends N{constructor(o,i){let s=b.parse(i),r;if(s.baseUrl)r=s.baseUrl;else if(s.location&&s.projectId)r=ee.baseUrl(s.location,s.projectId,s.publisher);else throw new ye({info:"Either 'baseUrl' must be provided or 'location' and 'projectId' must be provided",cause:new Error("Either 'baseUrl' must be provided or 'location' and 'projectId' must be provided")});super(o,{modelName:s.modelName,apiKey:"random-api-key",completeChatUrl:`${r}/models/${s.modelName}:generateContent`,streamChatUrl:`${r}/models/${s.modelName}:streamGenerateContent`});this.version="v1";this.modelSchema=o,this.modelName=s.modelName,this.accessToken=s.accessToken,this.location=s.location,this.projectId=s.projectId,this.publisher=s.publisher;}getDefaultHeaders(){return wt(ne({},super.getDefaultHeaders()),{Authorization:`Bearer ${this.accessToken}`})}};var pn="gemini-1.0-pro",mt=Se,un=b,Le=class extends y{constructor(e){super(mt,e);}};var gn="gemini-1.0-pro-001",dt=Ge,hn=b,Fe=class extends y{constructor(e){super(dt,e);}};var fn="gemini-1.0-pro-vision",ct=Pe,yn=b,$e=class extends y{constructor(e){super(ct,e);}};var bn="gemini-1.5-flash-001",pt=ke,_n=b,qe=class extends y{constructor(e){super(pt,e);}};var En="gemini-1.5-flash-002",ut=Ie,Tn=b,Be=class extends y{constructor(e){super(ut,e);}};var Mn="gemini-1.5-flash",gt=we,xn=b,Ue=class extends y{constructor(e){super(gt,e);}};var vn="gemini-1.5-pro-001",ht=Re,Cn=b,Ae=class extends y{constructor(e){super(ht,e);}};var On="gemini-1.5-pro-002",ft=Ne,Sn=b,De=class extends y{constructor(e){super(ft,e);}};var Gn="gemini-1.5-pro",yt=je,Pn=b,Ve=class extends y{constructor(e){super(yt,e);}};var X=[M],Q=zod.z.enum([M]);var Rn=zod.z.object({predictions:zod.z.array(zod.z.object({embeddings:zod.z.object({values:zod.z.array(zod.z.number()),statistics:zod.z.object({token_count:zod.z.number(),truncated:zod.z.boolean()})})}))});var Nn=zod.z.object({model:zod.z.string().min(1).optional(),instances:zod.z.array(zod.z.object({content:zod.z.string().min(1)})).min(1),parameters:zod.z.object({auto_truncate:zod.z.boolean().optional(),output_dimensionality:zod.z.number().int().min(1).optional(),autoTruncate:zod.z.boolean().optional(),outputDimensionality:zod.z.number().int().min(1).optional()}).optional()});var K=zod.z.object({accessToken:zod.z.string(),modelName:zod.z.string(),baseUrl:zod.z.string().url().optional(),location:zod.z.string().optional(),projectId:zod.z.string().optional(),publisher:zod.z.string().optional()}),q=class{constructor(e,o){this.version="v1";let i=K.parse(o);this.modelSchema=e,this.modelName=i.modelName,this.accessToken=i.accessToken;let s;if(i.baseUrl)s=i.baseUrl;else if(i.location&&i.projectId)s=ee.baseUrl(i.location,i.projectId,i.publisher);else throw new ye({info:"Either 'baseUrl' must be provided or 'location' and 'projectId' must be provided",cause:new Error("Either 'baseUrl' must be provided or 'location' and 'projectId' must be provided")});this.baseUrl=s,this.getEmbeddingsUrl=`${this.baseUrl}/models/${i.modelName}:predict`,this.location=i.location,this.projectId=i.projectId;}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`}}getDefaultParams(){return {}}getRetryDelay(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.requests.reduce((o,i)=>o+i.length,0)}transformModelRequest(e){var c,p,g,f;let o=Nn.safeParse(e);if(!o.success)throw new V({info:"Invalid model request",cause:o.error});let i=o.data,s=i.model,r={autoTruncate:((c=i.parameters)==null?void 0:c.auto_truncate)||((p=i.parameters)==null?void 0:p.autoTruncate),dimensions:((g=i.parameters)==null?void 0:g.output_dimensionality)||((f=i.parameters)==null?void 0:f.outputDimensionality)},d=ce().parse(ge(r)),m={modality:M,requests:i.instances.map(h=>h.content)};return {modelName:s,config:d,embeddingRequests:m}}transformConfig(e,o){let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let s=i.data;return Object.keys(s).forEach(d=>{if(!this.modelSchema.config.def[d])throw new F({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${d}',
|
|
17
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),{parameters:Object.keys(s).reduce((d,m)=>{let p=this.modelSchema.config.def[m].param,g=s[m];return d[p]=g,d},{})}}transformEmbeddingRequests(e){let o=fe().safeParse(e);if(!o.success)throw new J({info:"Invalid embedding requests",cause:o.error});if(e.modality!==M)throw new J({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${M}' modality is supported for model : '${this.modelName}'`)});return {instances:o.data.requests.map(s=>({content:s}))}}getGetEmbeddingsUrl(e,o){return he(this,null,function*(){return new Promise(i=>{i(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,o){return he(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,o){return he(this,null,function*(){return new Promise(i=>{if(o.requests.length===0)throw new J({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});i(ne(ne(ne({},this.getDefaultParams()),this.transformConfig(e)),this.transformEmbeddingRequests(o)));})})}transformGetEmbeddingsResponse(e){let o=Rn.safeParse(e);if(o.success){let s=o.data.predictions.map((r,d)=>({index:d,embedding:r.embeddings.values}));return {encodingFormat:pe,embeddings:s}}throw new D({info:"Invalid response from model",cause:o.error})}};var Ot=t=>j({param:"output_dimensionality",title:ie.DIMENSIONS.title,description:ie.DIMENSIONS.description,min:1,max:t,step:1,default:t}),St=Eo({param:"auto_truncate",title:"Auto truncate",description:"When set to true, input text will be truncated. When set to false, an error is returned if the input text is longer than the maximum length supported by the model.",default:!0});var Ln=t=>zod.z.object({dimensions:Ot(t).schema,autoTruncate:St.schema}),Fn=t=>({dimensions:Ot(t).def,autoTruncate:St.def});var k={base:t=>({def:Fn(t),schema:Ln(t)})};var bt="text-embedding-004",Cs="text-embedding-004",_t=R(Q).parse({name:bt,description:Cs,modalities:X,maxInputTokens:2048,maxOutputTokens:768,config:{def:k.base(768).def,schema:k.base(768).schema}}),wn=K,ze=class extends q{constructor(e){super(_t,e);}};var Et="text-multilingual-embedding-002",Os="text-multilingual-embedding-002",Tt=R(Q).parse({name:Et,description:Os,modalities:X,maxInputTokens:2048,maxOutputTokens:768,config:{def:k.base(768).def,schema:k.base(768).schema}}),kn=K,He=class extends q{constructor(e){super(Tt,e);}};var Mt="textembedding-gecko-multilingual@001",Ss="textembedding-gecko-multilingual@001",xt=R(Q).parse({name:Mt,description:Ss,modalities:X,maxInputTokens:2048,maxOutputTokens:768,config:{def:k.base(768).def,schema:k.base(768).schema}}),In=K,Ke=class extends q{constructor(e){super(xt,e);}};var vt="textembedding-gecko@003",Gs="textembedding-gecko@003",Ct=R(Q).parse({name:vt,description:Gs,modalities:X,maxInputTokens:2048,maxOutputTokens:768,config:{def:k.base(768).def,schema:k.base(768).schema}}),jn=K,Ye=class extends q{constructor(e){super(Ct,e);}};
|
|
18
18
|
|
|
19
19
|
exports.BaseChatModelOptions = b;
|
|
20
20
|
exports.BaseChatModelVertex = y;
|