@adaline/vertex 1.10.7 → 1.12.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 CHANGED
@@ -3,20 +3,20 @@
3
3
  var jose = require('jose');
4
4
  var zod = require('zod');
5
5
 
6
- var ba=Object.defineProperty,Ta=Object.defineProperties;var Pa=Object.getOwnPropertyDescriptors;var an=Object.getOwnPropertySymbols;var Ma=Object.prototype.hasOwnProperty,va=Object.prototype.propertyIsEnumerable;var vt=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),ka=e=>{throw TypeError(e)};var sn=(e,t,n)=>t in e?ba(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))Ma.call(t,n)&&sn(e,n,t[n]);if(an)for(var n of an(t))va.call(t,n)&&sn(e,n,t[n]);return e},P=(e,t)=>Ta(e,Pa(t));var Z=(e,t,n)=>new Promise((i,s)=>{var m=l=>{try{d(n.next(l));}catch(p){s(p);}},r=l=>{try{d(n.throw(l));}catch(p){s(p);}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(m,r);d((n=n.apply(e,t)).next());}),_a=function(e,t){this[0]=e,this[1]=t;};var rn=e=>{var t=e[vt("asyncIterator")],n=!1,i,s={};return t==null?(t=e[vt("iterator")](),i=m=>s[m]=r=>t[m](r)):(t=t.call(e),i=m=>s[m]=r=>{if(n){if(n=!1,m==="throw")throw r;return r}return n=!0,{done:!1,value:new _a(new Promise(d=>{var l=t[m](r);l instanceof Object||ka("Object expected"),d(l);}),1)}}),s[vt("iterator")]=()=>s,i("next"),"throw"in t?i("throw"):s.throw=m=>{throw m},"return"in t&&i("return"),s};var Ee="system",Q="user",E="assistant",re="tool",xa=[Ee,Q,E,re],xt=zod.z.enum(xa),Sa=[E],Ea=zod.z.enum(Sa),be="error",Re="safety",Ca=zod.z.object({type:zod.z.literal(Re),value:zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean(),message:zod.z.string()})}),cn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(be),value:zod.z.discriminatedUnion("type",[Ca]),metadata:e}),St="partial-error",wa=zod.z.object({type:zod.z.literal(Re),category:zod.z.string().optional(),probability:zod.z.string().optional(),blocked:zod.z.boolean().optional(),message:zod.z.string().optional()}),pn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(St),value:zod.z.discriminatedUnion("type",[wa]),metadata:e}),le="image",Et="base64",Ga=["png","jpeg","webp","gif"],Oa=zod.z.object({type:zod.z.literal(Et),base64:zod.z.string(),mediaType:zod.z.enum(Ga)}),Ra="url",Ia=zod.z.object({type:zod.z.literal(Ra),url:zod.z.string()}),ja=zod.z.discriminatedUnion("type",[Oa,Ia]),Fa=["low","medium","high","auto"],La=zod.z.enum(Fa),Na=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(le),detail:La,value:ja,metadata:e}),ue="pdf",Ua="base64",Da=zod.z.object({type:zod.z.literal(Ua),base64:zod.z.string()}),$a="url",Ba=zod.z.object({type:zod.z.literal($a),url:zod.z.string()}),Aa=zod.z.discriminatedUnion("type",[Da,Ba]),qa=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ue),value:Aa,file:zod.z.object({name:zod.z.string(),id:zod.z.string(),size:zod.z.number().optional()}),metadata:e}),ge="reasoning",Ct="partial-reasoning",Ie="thinking",Ha="redacted",_t=zod.z.object({type:zod.z.literal(Ie),thinking:zod.z.string(),signature:zod.z.string()}),un=zod.z.object({type:zod.z.literal(Ha),data:zod.z.string()}),za=zod.z.discriminatedUnion("type",[_t,un]),gn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ge),value:za,metadata:e}),Va=zod.z.object({type:zod.z.literal(Ie),thinking:_t.shape.thinking.optional(),signature:_t.shape.signature.optional()}),Ka=zod.z.discriminatedUnion("type",[Va,un]),hn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ct),value:Ka,metadata:e}),Te="search-result",je="google",Ya=zod.z.object({type:zod.z.literal(je),query:zod.z.string(),responses:zod.z.array(zod.z.object({source:zod.z.string(),url:zod.z.string(),title:zod.z.string(),snippet:zod.z.string().optional()})),references:zod.z.array(zod.z.object({text:zod.z.string(),responseIndices:zod.z.array(zod.z.number()),startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),confidenceScores:zod.z.array(zod.z.number()).optional()}))}),fn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Te),value:zod.z.discriminatedUnion("type",[Ya]),metadata:e}),wt="partial-search-result",Wa=zod.z.object({type:zod.z.literal(je),query:zod.z.string().optional(),responses:zod.z.array(zod.z.object({source:zod.z.string().optional(),url:zod.z.string().optional(),title:zod.z.string().optional(),snippet:zod.z.string().optional()})).optional(),references:zod.z.array(zod.z.object({text:zod.z.string().optional(),responseIndices:zod.z.array(zod.z.number()).optional(),startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),confidenceScores:zod.z.array(zod.z.number()).optional()})).optional()}),yn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(wt),value:zod.z.discriminatedUnion("type",[Wa]),metadata:e}),B="text",bn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(B),value:zod.z.string(),metadata:e}),Gt="partial-text",Tn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Gt),value:zod.z.string(),metadata:e}),Y="tool-call",Pn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Y),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),serverName:zod.z.string().optional(),metadata:e}),Ot="partial-tool-call",Mn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ot),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),serverName:zod.z.string().optional(),metadata:e}),me="tool-response",Ja=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(me),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),apiResponse:zod.z.object({statusCode:zod.z.number().int().nonnegative()}).optional(),metadata:e}),Xa="partial-tool-response",Za=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Xa),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),data:zod.z.string().optional(),apiResponse:zod.z.object({statusCode:zod.z.number().int().nonnegative()}).optional(),metadata:e}),Qa=[B,le,ue,Y,me,ge,be,Te],vn=zod.z.enum(Qa),es=(e=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined(),r=zod.z.undefined(),d=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[bn(e),Na(t),qa(n),Pn(i),Ja(s),gn(m),cn(r),fn(d)]),ts=[Gt,Ot,Ct,St,wt];zod.z.enum(ts);var os=(e=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Tn(e),Mn(t),hn(i),Za(n),pn(s),yn(m)]);var Rt=(e=xt,t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined(),r=zod.z.undefined(),d=zod.z.undefined())=>zod.z.object({role:e,content:zod.z.array(es(t,n,i,s,r,m)),metadata:d}),Pe=(e=Ea,t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined())=>zod.z.object({role:e,partialContent:os(t,n,i,m),metadata:s}),ns=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),ln=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),is=ln.extend({topLogProbs:zod.z.array(ln)}),kn=zod.z.array(is);zod.z.object({messages:zod.z.array(Rt()),usage:ns.optional(),logProbs:kn.optional()});var as=zod.z.object({promptTokens:zod.z.number().nonnegative().optional(),completionTokens:zod.z.number().nonnegative().optional(),totalTokens:zod.z.number().nonnegative().optional()});zod.z.object({partialMessages:zod.z.array(Pe()),usage:as.optional(),logProbs:kn.optional()});var Ce=(e=zod.z.record(zod.z.string(),zod.z.any()).optional())=>e,ss=zod.z.object({enabled:zod.z.boolean().default(!0),allowedTools:zod.z.array(zod.z.string().min(1))});zod.z.object({type:zod.z.literal("url"),url:zod.z.string().url().refine(e=>e.startsWith("https://"),{message:"MCP server URL must start with https://"}),name:zod.z.string().min(1),toolConfiguration:ss.optional(),authorizationToken:zod.z.string().min(1).optional()});var rs=["object","array","number","string","boolean","enum"],mn=zod.z.enum(rs),ls=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([mn,zod.z.array(zod.z.union([mn,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()}),ms=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(ls),additionalProperties:zod.z.literal(!1)}),_n=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:ms}).optional(),A="text",xn="token",ds=[A,xn],Sn=zod.z.enum(ds),cs=zod.z.array(zod.z.string().min(1)),ps=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),Fe=(e=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(A),metadata:e,requests:cs}),zod.z.object({modality:zod.z.literal(xn),metadata:e,requests:ps})]),we="float",us=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),gs="base64",hs=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),dn=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(we),embeddings:zod.z.array(us),usage:dn.optional()}),zod.z.object({encodingFormat:zod.z.literal(gs),embeddings:zod.z.array(hs),usage:dn.optional()})]);var fs=e=>{let t=new WeakSet;return JSON.stringify(e,(n,i)=>{if(typeof i=="object"&&i!==null){if(t.has(i))return;t.add(i);}return i})},ys=e=>e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:fs(e),kt="GatewayBaseError",ne=class En extends Error{constructor({info:t,cause:n},i){super(`[${i!=null?i:kt}]: ${t}
7
- Message: ${ys(n)}`),this.name=kt,this.info=t,this.cause=n,this.name=i!=null?i:kt,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof En}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},bs=zod.z.object({inputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M input tokens"),outputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M output tokens")}).describe("Input/output price pair (per 1M tokens) for a specific category within a ChatModel pricing tier."),Ts=zod.z.object({base:bs.describe("Base (uncached, non\u2011reasoning) rates")}).describe("Holds the `ChatModelTokenPairPrice` for different categories (e.g., base) within a single pricing tier."),Ps=zod.z.object({minTokens:zod.z.number().int().nonnegative().describe("Inclusive lower token bound for this tier."),maxTokens:zod.z.number().int().nullable().optional().describe("Exclusive upper token bound; `null` means \u221E."),prices:Ts.describe("Price categories and rates for this specific token range.")}).refine(e=>e.maxTokens===null||typeof e.maxTokens=="number"&&e.maxTokens>e.minTokens,{message:"maxTokens must be > minTokens (or null for infinite).",path:["maxTokens"]}).describe("A single pricing tier defined by a token range and associated prices.");zod.z.object({modelName:zod.z.string().describe("Model name this schedule applies to."),currency:zod.z.string().default("USD").describe("Currency code (e.g., USD)."),tokenRanges:zod.z.array(Ps).min(1).describe("Pricing tiers (`ChatModelTokenRangePrice`) schedule, sorted by minTokens.")}).superRefine((e,t)=>{let{tokenRanges:n}=e;n[0].minTokens!==0&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",0,"minTokens"],message:"The first tier must have minTokens = 0."});for(let s=1;s<n.length;s++){let m=n[s-1],r=n[s];if(m.maxTokens===null){t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",s-1,"maxTokens"],message:"Cannot define any tokenRanges after an infinite tier (maxTokens = null)."});break}r.minTokens!==m.maxTokens&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",s,"minTokens"],message:`Tier ${s} minTokens (${r.minTokens}) must equal previous tier's maxTokens (${m.maxTokens}) for contiguity.`}),r.minTokens<m.minTokens&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",s,"minTokens"],message:`tokenRanges must be sorted by ascending minTokens. Tier ${s} (${r.minTokens}) starts before Tier ${s-1} (${m.minTokens}).`});}let i=n[n.length-1];n.every(s=>s.maxTokens!==null||s===i)&&i.maxTokens!==null&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",n.length-1,"maxTokens"],message:"The final tier must have maxTokens = null (representing infinity)."});}).describe("Complete pricing schedule for a single chat model, including all its token-based tiers.");var Ms="function";var vs=zod.z.enum(["object","array","number","string","boolean","null"]),ks=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:vs.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(ks).optional(),required:zod.z.array(zod.z.string()).optional()});var _s=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 xs=zod.z.enum(["function"]),Ss=zod.z.object({maxAttempts:zod.z.number().int().positive(),initialDelay:zod.z.number().int().positive(),exponentialFactor:zod.z.number().int().positive()}),Es=zod.z.object({type:zod.z.literal("http"),method:zod.z.enum(["get","post"]),url:zod.z.string().url(),headers:zod.z.record(zod.z.string()).optional(),query:zod.z.record(zod.z.string()).optional(),body:zod.z.record(zod.z.any()).optional(),proxyUrl:zod.z.string().url().optional(),proxyHeaders:zod.z.record(zod.z.string()).optional(),retry:Ss.optional()}),Cs=zod.z.discriminatedUnion("type",[Es]),ws=zod.z.object({type:xs,definition:zod.z.object({schema:_s}),request:Cs.optional()}),Gs=[Ms];zod.z.enum(Gs);var Cn=(e=zod.z.undefined())=>zod.z.discriminatedUnion("type",[ws.extend({metadata:e})]),wn=e=>bn().parse({modality:B,value:e}),Gn=(e,t,n,i,s)=>Pn().parse({modality:Y,index:e,id:t,name:n,arguments:i,serverName:s});var It=(e,t)=>Pe().parse({role:e,partialContent:Tn().parse({modality:Gt,value:t})}),jt=(e,t,n,i,s,m)=>Pe().parse({role:e,partialContent:Mn().parse({modality:Ot,index:t,id:n,name:i,arguments:s,serverName:m})});var On=(e,t)=>gn().parse({modality:ge,value:{type:Ie,thinking:e,signature:t}});var Ft=(e,t,n)=>Pe().parse({role:e,partialContent:hn().parse({modality:Ct,value:{type:Ie,thinking:t,signature:n}})});var Lt=(e,t,n,i)=>cn().parse({modality:be,value:{type:Re,value:{category:e,probability:t,blocked:n,message:i}}});var Nt=(e,t,n,i,s)=>Pe().parse({role:e,partialContent:pn().parse({modality:St,value:{type:Re,category:t,probability:n,blocked:i,message:s}})}),Ut=(e,t,n)=>fn().parse({modality:Te,value:{type:je,query:e,responses:t,references:n}});var Dt=(e,t,n,i)=>Pe().parse({role:e,partialContent:yn().parse({modality:wt,value:{type:je,query:t,responses:n,references:i}})});var Os=Object.defineProperty,Rn=Object.getOwnPropertySymbols,Rs=Object.prototype.hasOwnProperty,Is=Object.prototype.propertyIsEnumerable,In=(e,t,n)=>t in e?Os(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Me=(e,t)=>{for(var n in t||(t={}))Rs.call(t,n)&&In(e,n,t[n]);if(Rn)for(var n of Rn(t))Is.call(t,n)&&In(e,n,t[n]);return e},jn="ProviderError",ve=class qn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},jn),this.name=jn,this.info=t,this.cause=n;}static isProviderError(t){return t instanceof qn}},Fn="ModelError",ke=class Hn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Fn),this.name=Fn,this.info=t,this.cause=n;}static isModelError(t){return t instanceof Hn}},Ln="ModelResponseError",H=class zn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Ln),this.name=Ln,this.cause=n,this.info=t;}static isModelResponseError(t){return t instanceof zn}},Nn="InvalidModelRequestError",ie=class Vn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Nn),this.name=Nn,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(t){return t instanceof Vn}},Un="InvalidConfigError",V=class Kn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Un),this.name=Un,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(t){return t instanceof Kn}},Dn="InvalidMessagesError",C=class Yn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Dn),this.name=Dn,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(t){return t instanceof Yn}},$n="InvalidToolsError",$t=class Wn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},$n),this.name=$n,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof Wn}},Bn="InvalidEmbeddingRequestsError",de=class Jn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Bn),this.name=Bn,this.info=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(t){return t instanceof Jn}},Bt="multi-string",Xn=zod.z.object({type:zod.z.literal(Bt),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()}),js=e=>zod.z.array(zod.z.string()).max(e).default([]).optional(),Zn=e=>({def:Xn.parse(Me({type:Bt},e)),schema:js(e.max)}),At="object-schema",Qn=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()}),Fs=e=>e.optional(),ei=e=>({def:Qn.parse(Me({type:At},e)),schema:Fs(e.objectSchema)}),qt="paired-select",Ls=zod.z.object({value:zod.z.string().min(1),label:zod.z.string().min(1)}),An=zod.z.object({key:zod.z.string().min(1),label:zod.z.string().min(1),description:zod.z.string().min(1).max(500).optional(),choices:zod.z.array(Ls).min(1)}),ti=zod.z.object({type:zod.z.literal(qt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),fields:zod.z.tuple([An,An]),uniqueByField:zod.z.string().min(1).optional()}),Ns=e=>{let t=e.map(s=>s.value);if(t.length===0)throw new Error("PairedSelectConfigItem fields must define at least one choice");let[n,...i]=t;return zod.z.enum([n,...i])},Us=e=>{let t=e.reduce((n,i)=>(n[i.key]=Ns(i.choices),n),{});return zod.z.array(zod.z.object(t)).optional()},oi=e=>{let t=ti.parse(Me({type:qt},e)),n=new Set(t.fields.map(i=>i.key));if(n.size!==t.fields.length)throw new Error("PairedSelectConfigItem fields must have unique keys");if(t.uniqueByField&&!n.has(t.uniqueByField))throw new Error("uniqueByField must reference one of the defined field keys");return {def:t,schema:Us(t.fields)}},Ht="range",ni=zod.z.object({type:zod.z.literal(Ht),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()}),Ds=(e,t,n,i)=>zod.z.number().min(e).max(t).step(n).default(i).optional(),W=e=>({def:ni.parse(Me({type:Ht},e)),schema:Ds(e.min,e.max,e.step,e.default)}),zt="select-boolean",ii=zod.z.object({type:zod.z.literal(zt),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()}),$s=e=>zod.z.boolean().nullable().default(e).optional(),Ge=e=>({def:ii.parse(Me({type:zt},e)),schema:$s(e.default)}),Vt="select-string",ai=zod.z.object({type:zod.z.literal(Vt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string(),choices:zod.z.array(zod.z.string())}),Bs=(e,t)=>zod.z.enum(t).nullable().default(e).optional(),Le=e=>({def:ai.parse(Me({type:Vt},e)),schema:Bs(e.default,e.choices)}),As=[Ht,Bt,Vt,At,zt,qt];zod.z.enum(As);var si=zod.z.discriminatedUnion("type",[ni,Xn,ai,ii,Qn,ti]),I=(e=xt,t=vn)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(e,zod.z.string().min(1).optional()),modalities:zod.z.array(t).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),maxReasoningTokens:zod.z.number().int().positive().min(1).optional(),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),si),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(n=>{var i,s;let m=Object.keys(n.def),r=Object.keys((s=(i=n.schema)==null?void 0:i.shape)!=null?s:{});return m.every(d=>r.includes(d))&&r.every(d=>m.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"}),price:zod.z.custom()}),J=(e=Sn)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),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),si),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(t=>{var n,i;let s=Object.keys(t.def),m=Object.keys((i=(n=t.schema)==null?void 0:n.shape)!=null?i:{});return s.every(r=>m.includes(r))&&m.every(r=>s.includes(r))},{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 qs={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."},Hs={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."},zs={type:"range",title:"Max reasoning tokens",description:"Specify the total tokens for reasoning, where one token approximates four English characters."},Vs=e=>({type:"multi",title:"Stop sequence",description:`Enter up to ${e} sequences that will halt additional text output. The generated text will exclude these sequences.`}),Ks={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."},Ys={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."},Ws={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."},Js={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."},Xs={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."},Zs={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."},Qs={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."},er={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."},tr={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."},or={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."},nr={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},ir={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."},ar={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."},sr={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."},rr={type:"object",title:"MCP servers",description:"MCP servers to use for the model."},O={TEMPERATURE:qs,MAX_TOKENS:Hs,STOP:Vs,TOP_A:Ks,TOP_P:Ys,TOP_K:Ws,MIN_P:Js,FREQUENCY_PENALTY:Xs,PRESENCE_PENALTY:Zs,REPETITION_PENALTY:er,SEED:Qs,LOG_PROBS:tr,TOP_LOG_PROBS:or,ECHO:nr,RESPONSE_FORMAT:ir,RESPONSE_FORMAT_WITH_SCHEMA:ar,RESPONSE_SCHEMA:sr,MAX_REASONING_TOKENS:zs,MCP_SERVERS:rr},lr={type:"range",title:"Dimensions",description:"Select the number of dimensions for the word embedding."},mr={type:"select",title:"Encoding format",description:"Select the encoding format for the word embedding."},_e={DIMENSIONS:lr,ENCODING_FORMAT:mr};var Oe=e=>Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null)),Kt=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined",ri=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=globalThis.atob(t);return Uint8Array.from(n,i=>i.codePointAt(0))};var xe=e=>e==null?void 0:e.replace(/\/$/,"");var dr=Object.defineProperty,cr=Object.defineProperties,pr=Object.getOwnPropertyDescriptors,li=Object.getOwnPropertySymbols,ur=Object.prototype.hasOwnProperty,gr=Object.prototype.propertyIsEnumerable,Ne=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),hr=e=>{throw TypeError(e)},mi=(e,t,n)=>t in e?dr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))ur.call(t,n)&&mi(e,n,t[n]);if(li)for(var n of li(t))gr.call(t,n)&&mi(e,n,t[n]);return e},he=(e,t)=>cr(e,pr(t)),j=(e,t,n)=>new Promise((i,s)=>{var m=l=>{try{d(n.next(l));}catch(p){s(p);}},r=l=>{try{d(n.throw(l));}catch(p){s(p);}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(m,r);d((n=n.apply(e,t)).next());}),bi=function(e,t){this[0]=e,this[1]=t;},di=(e,t,n)=>{var i=(r,d,l,p)=>{try{var h=n[r](d),y=(d=h.value)instanceof bi,u=h.done;Promise.resolve(y?d[0]:d).then(g=>y?i(r==="return"?r:"next",d[1]?{done:g.done,value:g.value}:g,l,p):l({value:g,done:u})).catch(g=>i("throw",g,l,p));}catch(g){p(g);}},s=r=>m[r]=d=>new Promise((l,p)=>i(r,d,l,p)),m={};return n=n.apply(e,t),m[Ne("asyncIterator")]=()=>m,s("next"),s("throw"),s("return"),m},fr=e=>{var t=e[Ne("asyncIterator")],n=!1,i,s={};return t==null?(t=e[Ne("iterator")](),i=m=>s[m]=r=>t[m](r)):(t=t.call(e),i=m=>s[m]=r=>{if(n){if(n=!1,m==="throw")throw r;return r}return n=!0,{done:!1,value:new bi(new Promise(d=>{var l=t[m](r);l instanceof Object||hr("Object expected"),d(l);}),1)}}),s[Ne("iterator")]=()=>s,i("next"),"throw"in t?i("throw"):s.throw=m=>{throw m},"return"in t&&i("return"),s},yr=["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"],br=["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"],Ti=(e,t)=>e.replace(t,"").replace(/_/g," ").toLowerCase().replace(/\b\w/g,n=>n.toUpperCase()),Tr=yr.map(e=>({value:e,label:Ti(e,"HARM_CATEGORY_")})),Pr=br.map(e=>({value:e,label:Ti(e,"HARM_BLOCK_THRESHOLD_")})),Pi=(e,t)=>W({param:"temperature",title:O.TEMPERATURE.title,description:O.TEMPERATURE.description,min:0,max:e,step:.01,default:t}),Mi=e=>W({param:"maxOutputTokens",title:O.MAX_TOKENS.title,description:O.MAX_TOKENS.description,min:0,max:e,step:1,default:0}),vi=e=>Zn({param:"stopSequences",title:O.STOP(e).title,description:O.STOP(e).description,max:e}),ki=e=>W({param:"topP",title:O.TOP_P.title,description:O.TOP_P.description,min:0,max:1,step:.01,default:e});W({param:"frequencyPenalty",title:O.FREQUENCY_PENALTY.title,description:O.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0});W({param:"presencePenalty",title:O.PRESENCE_PENALTY.title,description:O.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0});W({param:"seed",title:O.SEED.title,description:O.SEED.description,min:0,max:1e6,step:1,default:0});var _i=Le({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"]}),xi=oi({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.",fields:[{key:"category",label:"Category",choices:Tr},{key:"threshold",label:"Threshold",choices:Pr}],uniqueByField:"category"}),Si=Ge({param:"reasoningEnabled",title:"Reasoning Enabled",description:"Controls whether the model is allowed to think for a longer period of time before generating a response. This can be useful for complex tasks that require more time to think.",default:!1}),Ei=(e,t)=>W({param:"thinkingBudget",title:"Thinking budget",description:"Specify the total tokens for thinking (or reasoning), where one token approximates four English characters.",min:e,max:t,step:1,default:0}),Ci=Le({param:"thinkingLevel",title:"Thinking Level",description:"Controls the depth of the model's reasoning process. Higher levels may result in more thorough reasoning but use more tokens.",default:"LOW",choices:["LOW","HIGH"]}),wi=Ge({param:"googleSearch",title:"Google Search Tool",description:"Controls whether the model is allowed to use the Google Search tool. Powered by Google.",default:!1}),Gi=(e,t,n,i,s)=>zod.z.object({temperature:Pi(e,t).schema,maxTokens:Mi(n).schema,stop:vi(i).schema,topP:ki(s).schema,toolChoice:_i.schema,safetySettings:xi.schema,googleSearchTool:wi.schema}),Oi=(e,t,n,i,s)=>({temperature:Pi(e,t).def,maxTokens:Mi(n).def,stop:vi(i).def,topP:ki(s).def,toolChoice:_i.def,safetySettings:xi.def,googleSearchTool:wi.def}),Ri=ei({param:"response_schema",title:O.RESPONSE_SCHEMA.title,description:O.RESPONSE_SCHEMA.description,objectSchema:_n}),Ii=Le({param:"response_format",title:O.RESPONSE_FORMAT_WITH_SCHEMA.title,description:O.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_schema"]}),ji=(e,t,n,i,s)=>he(S({},Oi(e,t,n,i,s)),{responseFormat:Ii.def,responseSchema:Ri.def}),Fi=(e,t,n,i,s)=>Gi(e,t,n,i,s).extend({responseFormat:Ii.schema,responseSchema:Ri.schema}),Mr=(e,t,n,i,s,m,r)=>Fi(e,t,n,i,s).extend({reasoningEnabled:Si.schema,maxReasoningTokens:Ei(m,r).schema,reasoningEffort:Ci.schema}),vr=(e,t,n,i,s,m,r)=>he(S({},ji(e,t,n,i,s)),{reasoningEnabled:Si.def,maxReasoningTokens:Ei(m,r).def,reasoningEffort:Ci.def}),Li=e=>W({param:"outputDimensionality",title:_e.DIMENSIONS.title,description:_e.DIMENSIONS.description,min:1,max:e,step:1,default:e}),kr=e=>zod.z.object({dimensions:Li(e).schema}),_r=e=>({dimensions:Li(e).def}),k={base:(e,t,n,i,s)=>({def:Oi(e,t,n,i,s),schema:Gi(e,t,n,i,s)}),responseSchema:(e,t,n,i,s)=>({def:ji(e,t,n,i,s),schema:Fi(e,t,n,i,s)}),reasoning:(e,t,n,i,s,m,r)=>({def:vr(e,t,n,i,s,m,r),schema:Mr(e,t,n,i,s,m,r)})},Ue={base:e=>({def:_r(e),schema:kr(e)})},xr="google",co=class{constructor(){this.version="v1",this.name=xr,this.chatModelFactories={[Yt]:{model:Wr,modelOptions:Yr,modelSchema:De},[Wt]:{model:Zr,modelOptions:Xr,modelSchema:$e},[Jt]:{model:tl,modelOptions:el,modelSchema:Be},[Xt]:{model:il,modelOptions:nl,modelSchema:Ae},[Zt]:{model:rl,modelOptions:sl,modelSchema:qe},[Qt]:{model:dl,modelOptions:ml,modelSchema:He},[eo]:{model:ul,modelOptions:pl,modelSchema:ze},[to]:{model:fl,modelOptions:hl,modelSchema:Ve},[oo]:{model:Pl,modelOptions:Tl,modelSchema:Ke},[io]:{model:Sl,modelOptions:xl,modelSchema:We},[so]:{model:Rl,modelOptions:Ol,modelSchema:Xe},[ao]:{model:wl,modelOptions:Cl,modelSchema:Je},[ro]:{model:Fl,modelOptions:jl,modelSchema:Ze},[lo]:{model:Ul,modelOptions:Nl,modelSchema:Qe},[mo]:{model:Bl,modelOptions:$l,modelSchema:et},[no]:{model:kl,modelOptions:vl,modelSchema:Ye}},this.embeddingModelFactories={[qi]:{model:Kl,modelOptions:Vl,modelSchema:Hi},[zi]:{model:Jl,modelOptions:Wl,modelSchema:Vi}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}chatModel(e){let t=e.modelName;if(!(t in this.chatModelFactories))throw new ve({info:`Google chat model: ${t} not found`,cause:new Error(`Google chat model: ${t} not found, available chat models:
6
+ var ba=Object.defineProperty,Ta=Object.defineProperties;var Pa=Object.getOwnPropertyDescriptors;var an=Object.getOwnPropertySymbols;var Ma=Object.prototype.hasOwnProperty,va=Object.prototype.propertyIsEnumerable;var vt=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),ka=e=>{throw TypeError(e)};var sn=(e,t,n)=>t in e?ba(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,b=(e,t)=>{for(var n in t||(t={}))Ma.call(t,n)&&sn(e,n,t[n]);if(an)for(var n of an(t))va.call(t,n)&&sn(e,n,t[n]);return e},P=(e,t)=>Ta(e,Pa(t));var Z=(e,t,n)=>new Promise((i,s)=>{var m=l=>{try{d(n.next(l));}catch(p){s(p);}},r=l=>{try{d(n.throw(l));}catch(p){s(p);}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(m,r);d((n=n.apply(e,t)).next());}),_a=function(e,t){this[0]=e,this[1]=t;};var rn=e=>{var t=e[vt("asyncIterator")],n=!1,i,s={};return t==null?(t=e[vt("iterator")](),i=m=>s[m]=r=>t[m](r)):(t=t.call(e),i=m=>s[m]=r=>{if(n){if(n=!1,m==="throw")throw r;return r}return n=!0,{done:!1,value:new _a(new Promise(d=>{var l=t[m](r);l instanceof Object||ka("Object expected"),d(l);}),1)}}),s[vt("iterator")]=()=>s,i("next"),"throw"in t?i("throw"):s.throw=m=>{throw m},"return"in t&&i("return"),s};var Ee="system",Q="user",E="assistant",re="tool",xa=[Ee,Q,E,re],xt=zod.z.enum(xa),Sa=[E],Ea=zod.z.enum(Sa),be="error",Re="safety",Ca=zod.z.object({type:zod.z.literal(Re),value:zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean(),message:zod.z.string()})}),cn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(be),value:zod.z.discriminatedUnion("type",[Ca]),metadata:e}),St="partial-error",wa=zod.z.object({type:zod.z.literal(Re),category:zod.z.string().optional(),probability:zod.z.string().optional(),blocked:zod.z.boolean().optional(),message:zod.z.string().optional()}),pn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(St),value:zod.z.discriminatedUnion("type",[wa]),metadata:e}),le="image",Et="base64",Oa=["png","jpeg","webp","gif"],Ga=zod.z.object({type:zod.z.literal(Et),base64:zod.z.string(),mediaType:zod.z.enum(Oa)}),Ra="url",Ia=zod.z.object({type:zod.z.literal(Ra),url:zod.z.string()}),ja=zod.z.discriminatedUnion("type",[Ga,Ia]),Fa=["low","medium","high","auto"],La=zod.z.enum(Fa),Na=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(le),detail:La,value:ja,metadata:e}),ue="pdf",Ua="base64",Da=zod.z.object({type:zod.z.literal(Ua),base64:zod.z.string()}),$a="url",Ba=zod.z.object({type:zod.z.literal($a),url:zod.z.string()}),Aa=zod.z.discriminatedUnion("type",[Da,Ba]),qa=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ue),value:Aa,file:zod.z.object({name:zod.z.string(),id:zod.z.string(),size:zod.z.number().optional()}),metadata:e}),ge="reasoning",Ct="partial-reasoning",Ie="thinking",za="redacted",_t=zod.z.object({type:zod.z.literal(Ie),thinking:zod.z.string(),signature:zod.z.string()}),un=zod.z.object({type:zod.z.literal(za),data:zod.z.string()}),Ha=zod.z.discriminatedUnion("type",[_t,un]),gn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(ge),value:Ha,metadata:e}),Va=zod.z.object({type:zod.z.literal(Ie),thinking:_t.shape.thinking.optional(),signature:_t.shape.signature.optional()}),Ka=zod.z.discriminatedUnion("type",[Va,un]),hn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ct),value:Ka,metadata:e}),Te="search-result",je="google",Ya=zod.z.object({type:zod.z.literal(je),query:zod.z.string(),responses:zod.z.array(zod.z.object({source:zod.z.string(),url:zod.z.string(),title:zod.z.string(),snippet:zod.z.string().optional()})),references:zod.z.array(zod.z.object({text:zod.z.string(),responseIndices:zod.z.array(zod.z.number()),startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),confidenceScores:zod.z.array(zod.z.number()).optional()}))}),fn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Te),value:zod.z.discriminatedUnion("type",[Ya]),metadata:e}),wt="partial-search-result",Wa=zod.z.object({type:zod.z.literal(je),query:zod.z.string().optional(),responses:zod.z.array(zod.z.object({source:zod.z.string().optional(),url:zod.z.string().optional(),title:zod.z.string().optional(),snippet:zod.z.string().optional()})).optional(),references:zod.z.array(zod.z.object({text:zod.z.string().optional(),responseIndices:zod.z.array(zod.z.number()).optional(),startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),confidenceScores:zod.z.array(zod.z.number()).optional()})).optional()}),yn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(wt),value:zod.z.discriminatedUnion("type",[Wa]),metadata:e}),B="text",bn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(B),value:zod.z.string(),metadata:e}),Ot="partial-text",Tn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Ot),value:zod.z.string(),metadata:e}),Y="tool-call",Pn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Y),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),arguments:zod.z.string(),serverName:zod.z.string().optional(),thoughtSignature:zod.z.string().optional(),metadata:e}),Gt="partial-tool-call",Mn=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Gt),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),arguments:zod.z.string().optional(),serverName:zod.z.string().optional(),thoughtSignature:zod.z.string().optional(),metadata:e}),me="tool-response",Ja=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(me),index:zod.z.number().int().nonnegative(),id:zod.z.string().min(1),name:zod.z.string().min(1),data:zod.z.string(),apiResponse:zod.z.object({statusCode:zod.z.number().int().nonnegative()}).optional(),metadata:e}),Xa="partial-tool-response",Za=(e=zod.z.undefined())=>zod.z.object({modality:zod.z.literal(Xa),index:zod.z.number().int().nonnegative(),id:zod.z.string().optional(),name:zod.z.string().optional(),data:zod.z.string().optional(),apiResponse:zod.z.object({statusCode:zod.z.number().int().nonnegative()}).optional(),metadata:e}),Qa=[B,le,ue,Y,me,ge,be,Te],vn=zod.z.enum(Qa),es=(e=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined(),r=zod.z.undefined(),d=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[bn(e),Na(t),qa(n),Pn(i),Ja(s),gn(m),cn(r),fn(d)]),ts=[Ot,Gt,Ct,St,wt];zod.z.enum(ts);var os=(e=zod.z.undefined(),t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[Tn(e),Mn(t),hn(i),Za(n),pn(s),yn(m)]);var Rt=(e=xt,t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined(),r=zod.z.undefined(),d=zod.z.undefined())=>zod.z.object({role:e,content:zod.z.array(es(t,n,i,s,r,m)),metadata:d}),Pe=(e=Ea,t=zod.z.undefined(),n=zod.z.undefined(),i=zod.z.undefined(),s=zod.z.undefined(),m=zod.z.undefined())=>zod.z.object({role:e,partialContent:os(t,n,i,m),metadata:s}),ns=zod.z.object({promptTokens:zod.z.number().nonnegative(),completionTokens:zod.z.number().nonnegative(),totalTokens:zod.z.number().nonnegative()}),ln=zod.z.object({token:zod.z.string(),logProb:zod.z.number(),bytes:zod.z.array(zod.z.number().int()).nullable()}),is=ln.extend({topLogProbs:zod.z.array(ln)}),kn=zod.z.array(is);zod.z.object({messages:zod.z.array(Rt()),usage:ns.optional(),logProbs:kn.optional()});var as=zod.z.object({promptTokens:zod.z.number().nonnegative().optional(),completionTokens:zod.z.number().nonnegative().optional(),totalTokens:zod.z.number().nonnegative().optional()});zod.z.object({partialMessages:zod.z.array(Pe()),usage:as.optional(),logProbs:kn.optional()});var Ce=(e=zod.z.record(zod.z.string(),zod.z.any()).optional())=>e,ss=zod.z.object({enabled:zod.z.boolean().default(!0),allowedTools:zod.z.array(zod.z.string().min(1))});zod.z.object({type:zod.z.literal("url"),url:zod.z.string().url().refine(e=>e.startsWith("https://"),{message:"MCP server URL must start with https://"}),name:zod.z.string().min(1),toolConfiguration:ss.optional(),authorizationToken:zod.z.string().min(1).optional()});var rs=["object","array","number","string","boolean","enum"],mn=zod.z.enum(rs),ls=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:zod.z.union([mn,zod.z.array(zod.z.union([mn,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()}),ms=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(ls),additionalProperties:zod.z.literal(!1)}),_n=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:ms}).optional(),A="text",xn="token",ds=[A,xn],Sn=zod.z.enum(ds),cs=zod.z.array(zod.z.string().min(1)),ps=zod.z.array(zod.z.array(zod.z.number().int().nonnegative())),Fe=(e=zod.z.undefined())=>zod.z.discriminatedUnion("modality",[zod.z.object({modality:zod.z.literal(A),metadata:e,requests:cs}),zod.z.object({modality:zod.z.literal(xn),metadata:e,requests:ps})]),we="float",us=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.array(zod.z.number())}),gs="base64",hs=zod.z.object({index:zod.z.number().int().nonnegative(),embedding:zod.z.string().base64()}),dn=zod.z.object({totalTokens:zod.z.number().int().nonnegative()});zod.z.discriminatedUnion("encodingFormat",[zod.z.object({encodingFormat:zod.z.literal(we),embeddings:zod.z.array(us),usage:dn.optional()}),zod.z.object({encodingFormat:zod.z.literal(gs),embeddings:zod.z.array(hs),usage:dn.optional()})]);var fs=e=>{let t=new WeakSet;return JSON.stringify(e,(n,i)=>{if(typeof i=="object"&&i!==null){if(t.has(i))return;t.add(i);}return i})},ys=e=>e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:fs(e),kt="GatewayBaseError",ne=class En extends Error{constructor({info:t,cause:n},i){super(`[${i!=null?i:kt}]: ${t}
7
+ Message: ${ys(n)}`),this.name=kt,this.info=t,this.cause=n,this.name=i!=null?i:kt,Object.setPrototypeOf(this,new.target.prototype);}static isGatewayBaseError(t){return t instanceof En}toJSON(){return {name:this.name,info:this.info,cause:this.cause,message:this.message,stack:this.stack}}},bs=zod.z.object({inputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M input tokens"),outputPricePerMillion:zod.z.number().nonnegative().describe("Price per 1M output tokens")}).describe("Input/output price pair (per 1M tokens) for a specific category within a ChatModel pricing tier."),Ts=zod.z.object({base:bs.describe("Base (uncached, non\u2011reasoning) rates")}).describe("Holds the `ChatModelTokenPairPrice` for different categories (e.g., base) within a single pricing tier."),Ps=zod.z.object({minTokens:zod.z.number().int().nonnegative().describe("Inclusive lower token bound for this tier."),maxTokens:zod.z.number().int().nullable().optional().describe("Exclusive upper token bound; `null` means \u221E."),prices:Ts.describe("Price categories and rates for this specific token range.")}).refine(e=>e.maxTokens===null||typeof e.maxTokens=="number"&&e.maxTokens>e.minTokens,{message:"maxTokens must be > minTokens (or null for infinite).",path:["maxTokens"]}).describe("A single pricing tier defined by a token range and associated prices.");zod.z.object({modelName:zod.z.string().describe("Model name this schedule applies to."),currency:zod.z.string().default("USD").describe("Currency code (e.g., USD)."),tokenRanges:zod.z.array(Ps).min(1).describe("Pricing tiers (`ChatModelTokenRangePrice`) schedule, sorted by minTokens.")}).superRefine((e,t)=>{let{tokenRanges:n}=e;n[0].minTokens!==0&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",0,"minTokens"],message:"The first tier must have minTokens = 0."});for(let s=1;s<n.length;s++){let m=n[s-1],r=n[s];if(m.maxTokens===null){t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",s-1,"maxTokens"],message:"Cannot define any tokenRanges after an infinite tier (maxTokens = null)."});break}r.minTokens!==m.maxTokens&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",s,"minTokens"],message:`Tier ${s} minTokens (${r.minTokens}) must equal previous tier's maxTokens (${m.maxTokens}) for contiguity.`}),r.minTokens<m.minTokens&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",s,"minTokens"],message:`tokenRanges must be sorted by ascending minTokens. Tier ${s} (${r.minTokens}) starts before Tier ${s-1} (${m.minTokens}).`});}let i=n[n.length-1];n.every(s=>s.maxTokens!==null||s===i)&&i.maxTokens!==null&&t.addIssue({code:zod.z.ZodIssueCode.custom,path:["tokenRanges",n.length-1,"maxTokens"],message:"The final tier must have maxTokens = null (representing infinity)."});}).describe("Complete pricing schedule for a single chat model, including all its token-based tiers.");var Ms="function";var vs=zod.z.enum(["object","array","number","string","boolean","null"]),ks=zod.z.object({anyOf:zod.z.array(zod.z.any()).optional(),type:vs.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(ks).optional(),required:zod.z.array(zod.z.string()).optional()});var _s=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 xs=zod.z.enum(["function"]),Ss=zod.z.object({maxAttempts:zod.z.number().int().positive(),initialDelay:zod.z.number().int().positive(),exponentialFactor:zod.z.number().int().positive()}),Es=zod.z.object({type:zod.z.literal("http"),method:zod.z.enum(["get","post"]),url:zod.z.string().url(),headers:zod.z.record(zod.z.string()).optional(),query:zod.z.record(zod.z.string()).optional(),body:zod.z.record(zod.z.any()).optional(),proxyUrl:zod.z.string().url().optional(),proxyHeaders:zod.z.record(zod.z.string()).optional(),retry:Ss.optional()}),Cs=zod.z.discriminatedUnion("type",[Es]),ws=zod.z.object({type:xs,definition:zod.z.object({schema:_s}),request:Cs.optional()}),Os=[Ms];zod.z.enum(Os);var Cn=(e=zod.z.undefined())=>zod.z.discriminatedUnion("type",[ws.extend({metadata:e})]),wn=e=>bn().parse({modality:B,value:e}),On=(e,t,n,i,s,m)=>Pn().parse({modality:Y,index:e,id:t,name:n,arguments:i,serverName:s,thoughtSignature:m});var It=(e,t)=>Pe().parse({role:e,partialContent:Tn().parse({modality:Ot,value:t})}),jt=(e,t,n,i,s,m,r)=>Pe().parse({role:e,partialContent:Mn().parse({modality:Gt,index:t,id:n,name:i,arguments:s,serverName:m,thoughtSignature:r})});var Gn=(e,t)=>gn().parse({modality:ge,value:{type:Ie,thinking:e,signature:t}});var Ft=(e,t,n)=>Pe().parse({role:e,partialContent:hn().parse({modality:Ct,value:{type:Ie,thinking:t,signature:n}})});var Lt=(e,t,n,i)=>cn().parse({modality:be,value:{type:Re,value:{category:e,probability:t,blocked:n,message:i}}});var Nt=(e,t,n,i,s)=>Pe().parse({role:e,partialContent:pn().parse({modality:St,value:{type:Re,category:t,probability:n,blocked:i,message:s}})}),Ut=(e,t,n)=>fn().parse({modality:Te,value:{type:je,query:e,responses:t,references:n}});var Dt=(e,t,n,i)=>Pe().parse({role:e,partialContent:yn().parse({modality:wt,value:{type:je,query:t,responses:n,references:i}})});var Gs=Object.defineProperty,Rn=Object.getOwnPropertySymbols,Rs=Object.prototype.hasOwnProperty,Is=Object.prototype.propertyIsEnumerable,In=(e,t,n)=>t in e?Gs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Me=(e,t)=>{for(var n in t||(t={}))Rs.call(t,n)&&In(e,n,t[n]);if(Rn)for(var n of Rn(t))Is.call(t,n)&&In(e,n,t[n]);return e},jn="ProviderError",ve=class qn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},jn),this.name=jn,this.info=t,this.cause=n;}static isProviderError(t){return t instanceof qn}},Fn="ModelError",ke=class zn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Fn),this.name=Fn,this.info=t,this.cause=n;}static isModelError(t){return t instanceof zn}},Ln="ModelResponseError",H=class Hn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Ln),this.name=Ln,this.cause=n,this.info=t;}static isModelResponseError(t){return t instanceof Hn}},Nn="InvalidModelRequestError",ie=class Vn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Nn),this.name=Nn,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidModelRequestError(t){return t instanceof Vn}},Un="InvalidConfigError",V=class Kn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Un),this.name=Un,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidConfigError(t){return t instanceof Kn}},Dn="InvalidMessagesError",C=class Yn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Dn),this.name=Dn,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidMessagesError(t){return t instanceof Yn}},$n="InvalidToolsError",$t=class Wn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},$n),this.name=$n,this.cause=n,this.info=t,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidToolsError(t){return t instanceof Wn}},Bn="InvalidEmbeddingRequestsError",de=class Jn extends ne{constructor({info:t,cause:n}){super({info:t,cause:n},Bn),this.name=Bn,this.info=t,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}static isInvalidEmbeddingRequestsError(t){return t instanceof Jn}},Bt="multi-string",Xn=zod.z.object({type:zod.z.literal(Bt),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()}),js=e=>zod.z.array(zod.z.string()).max(e).default([]).optional(),Zn=e=>({def:Xn.parse(Me({type:Bt},e)),schema:js(e.max)}),At="object-schema",Qn=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()}),Fs=e=>e.optional(),ei=e=>({def:Qn.parse(Me({type:At},e)),schema:Fs(e.objectSchema)}),qt="paired-select",Ls=zod.z.object({value:zod.z.string().min(1),label:zod.z.string().min(1)}),An=zod.z.object({key:zod.z.string().min(1),label:zod.z.string().min(1),description:zod.z.string().min(1).max(500).optional(),choices:zod.z.array(Ls).min(1)}),ti=zod.z.object({type:zod.z.literal(qt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),fields:zod.z.tuple([An,An]),uniqueByField:zod.z.string().min(1).optional()}),Ns=e=>{let t=e.map(s=>s.value);if(t.length===0)throw new Error("PairedSelectConfigItem fields must define at least one choice");let[n,...i]=t;return zod.z.enum([n,...i])},Us=e=>{let t=e.reduce((n,i)=>(n[i.key]=Ns(i.choices),n),{});return zod.z.array(zod.z.object(t)).optional()},oi=e=>{let t=ti.parse(Me({type:qt},e)),n=new Set(t.fields.map(i=>i.key));if(n.size!==t.fields.length)throw new Error("PairedSelectConfigItem fields must have unique keys");if(t.uniqueByField&&!n.has(t.uniqueByField))throw new Error("uniqueByField must reference one of the defined field keys");return {def:t,schema:Us(t.fields)}},zt="range",ni=zod.z.object({type:zod.z.literal(zt),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()}),Ds=(e,t,n,i)=>zod.z.number().min(e).max(t).step(n).default(i).optional(),W=e=>({def:ni.parse(Me({type:zt},e)),schema:Ds(e.min,e.max,e.step,e.default)}),Ht="select-boolean",ii=zod.z.object({type:zod.z.literal(Ht),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()}),$s=e=>zod.z.boolean().nullable().default(e).optional(),Oe=e=>({def:ii.parse(Me({type:Ht},e)),schema:$s(e.default)}),Vt="select-string",ai=zod.z.object({type:zod.z.literal(Vt),param:zod.z.string().min(1),title:zod.z.string().min(1),description:zod.z.string().min(1).max(500),default:zod.z.string(),choices:zod.z.array(zod.z.string())}),Bs=(e,t)=>zod.z.enum(t).nullable().default(e).optional(),Le=e=>({def:ai.parse(Me({type:Vt},e)),schema:Bs(e.default,e.choices)}),As=[zt,Bt,Vt,At,Ht,qt];zod.z.enum(As);var si=zod.z.discriminatedUnion("type",[ni,Xn,ai,ii,Qn,ti]),I=(e=xt,t=vn)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),roles:zod.z.record(e,zod.z.string().min(1).optional()),modalities:zod.z.array(t).nonempty(),maxInputTokens:zod.z.number().int().positive().min(1),maxOutputTokens:zod.z.number().int().positive().min(1),maxReasoningTokens:zod.z.number().int().positive().min(1).optional(),config:zod.z.object({def:zod.z.record(zod.z.string().min(1),si),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(n=>{var i,s;let m=Object.keys(n.def),r=Object.keys((s=(i=n.schema)==null?void 0:i.shape)!=null?s:{});return m.every(d=>r.includes(d))&&r.every(d=>m.includes(d))},{message:"Keys in 'config.def' must exactly match keys in 'config.schema'"}),price:zod.z.custom()}),J=(e=Sn)=>zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),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),si),schema:zod.z.instanceof(zod.z.ZodObject)}).refine(t=>{var n,i;let s=Object.keys(t.def),m=Object.keys((i=(n=t.schema)==null?void 0:n.shape)!=null?i:{});return s.every(r=>m.includes(r))&&m.every(r=>s.includes(r))},{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 qs={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."},zs={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."},Hs={type:"range",title:"Max reasoning tokens",description:"Specify the total tokens for reasoning, where one token approximates four English characters."},Vs=e=>({type:"multi",title:"Stop sequence",description:`Enter up to ${e} sequences that will halt additional text output. The generated text will exclude these sequences.`}),Ks={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."},Ys={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."},Ws={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."},Js={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."},Xs={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."},Zs={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."},Qs={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."},er={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."},tr={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."},or={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."},nr={type:"boolean",title:"Echo",description:"If true, the response will contain the prompt."},ir={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."},ar={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."},sr={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."},rr={type:"object",title:"MCP servers",description:"MCP servers to use for the model."},G={TEMPERATURE:qs,MAX_TOKENS:zs,STOP:Vs,TOP_A:Ks,TOP_P:Ys,TOP_K:Ws,MIN_P:Js,FREQUENCY_PENALTY:Xs,PRESENCE_PENALTY:Zs,REPETITION_PENALTY:er,SEED:Qs,LOG_PROBS:tr,TOP_LOG_PROBS:or,ECHO:nr,RESPONSE_FORMAT:ir,RESPONSE_FORMAT_WITH_SCHEMA:ar,RESPONSE_SCHEMA:sr,MAX_REASONING_TOKENS:Hs,MCP_SERVERS:rr},lr={type:"range",title:"Dimensions",description:"Select the number of dimensions for the word embedding."},mr={type:"select",title:"Encoding format",description:"Select the encoding format for the word embedding."},_e={DIMENSIONS:lr,ENCODING_FORMAT:mr};var Ge=e=>Object.fromEntries(Object.entries(e).filter(([t,n])=>n!=null)),Kt=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined",ri=e=>{let t=e.replace(/-/g,"+").replace(/_/g,"/"),n=globalThis.atob(t);return Uint8Array.from(n,i=>i.codePointAt(0))};var xe=e=>e==null?void 0:e.replace(/\/$/,"");var dr=Object.defineProperty,cr=Object.defineProperties,pr=Object.getOwnPropertyDescriptors,li=Object.getOwnPropertySymbols,ur=Object.prototype.hasOwnProperty,gr=Object.prototype.propertyIsEnumerable,Ne=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),hr=e=>{throw TypeError(e)},mi=(e,t,n)=>t in e?dr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,S=(e,t)=>{for(var n in t||(t={}))ur.call(t,n)&&mi(e,n,t[n]);if(li)for(var n of li(t))gr.call(t,n)&&mi(e,n,t[n]);return e},he=(e,t)=>cr(e,pr(t)),j=(e,t,n)=>new Promise((i,s)=>{var m=l=>{try{d(n.next(l));}catch(p){s(p);}},r=l=>{try{d(n.throw(l));}catch(p){s(p);}},d=l=>l.done?i(l.value):Promise.resolve(l.value).then(m,r);d((n=n.apply(e,t)).next());}),bi=function(e,t){this[0]=e,this[1]=t;},di=(e,t,n)=>{var i=(r,d,l,p)=>{try{var h=n[r](d),y=(d=h.value)instanceof bi,u=h.done;Promise.resolve(y?d[0]:d).then(g=>y?i(r==="return"?r:"next",d[1]?{done:g.done,value:g.value}:g,l,p):l({value:g,done:u})).catch(g=>i("throw",g,l,p));}catch(g){p(g);}},s=r=>m[r]=d=>new Promise((l,p)=>i(r,d,l,p)),m={};return n=n.apply(e,t),m[Ne("asyncIterator")]=()=>m,s("next"),s("throw"),s("return"),m},fr=e=>{var t=e[Ne("asyncIterator")],n=!1,i,s={};return t==null?(t=e[Ne("iterator")](),i=m=>s[m]=r=>t[m](r)):(t=t.call(e),i=m=>s[m]=r=>{if(n){if(n=!1,m==="throw")throw r;return r}return n=!0,{done:!1,value:new bi(new Promise(d=>{var l=t[m](r);l instanceof Object||hr("Object expected"),d(l);}),1)}}),s[Ne("iterator")]=()=>s,i("next"),"throw"in t?i("throw"):s.throw=m=>{throw m},"return"in t&&i("return"),s},yr=["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"],br=["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"],Ti=(e,t)=>e.replace(t,"").replace(/_/g," ").toLowerCase().replace(/\b\w/g,n=>n.toUpperCase()),Tr=yr.map(e=>({value:e,label:Ti(e,"HARM_CATEGORY_")})),Pr=br.map(e=>({value:e,label:Ti(e,"HARM_BLOCK_THRESHOLD_")})),Pi=(e,t)=>W({param:"temperature",title:G.TEMPERATURE.title,description:G.TEMPERATURE.description,min:0,max:e,step:.01,default:t}),Mi=e=>W({param:"maxOutputTokens",title:G.MAX_TOKENS.title,description:G.MAX_TOKENS.description,min:0,max:e,step:1,default:0}),vi=e=>Zn({param:"stopSequences",title:G.STOP(e).title,description:G.STOP(e).description,max:e}),ki=e=>W({param:"topP",title:G.TOP_P.title,description:G.TOP_P.description,min:0,max:1,step:.01,default:e});W({param:"frequencyPenalty",title:G.FREQUENCY_PENALTY.title,description:G.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0});W({param:"presencePenalty",title:G.PRESENCE_PENALTY.title,description:G.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0});W({param:"seed",title:G.SEED.title,description:G.SEED.description,min:0,max:1e6,step:1,default:0});var _i=Le({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"]}),xi=oi({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.",fields:[{key:"category",label:"Category",choices:Tr},{key:"threshold",label:"Threshold",choices:Pr}],uniqueByField:"category"}),Si=Oe({param:"reasoningEnabled",title:"Reasoning Enabled",description:"Controls whether the model is allowed to think for a longer period of time before generating a response. This can be useful for complex tasks that require more time to think.",default:!1}),Ei=(e,t)=>W({param:"thinkingBudget",title:"Thinking budget",description:"Specify the total tokens for thinking (or reasoning), where one token approximates four English characters.",min:e,max:t,step:1,default:0}),Ci=Le({param:"thinkingLevel",title:"Thinking Level",description:"Controls the depth of the model's reasoning process. Higher levels may result in more thorough reasoning but use more tokens.",default:"LOW",choices:["LOW","HIGH"]}),wi=Oe({param:"googleSearch",title:"Google Search Tool",description:"Controls whether the model is allowed to use the Google Search tool. Powered by Google.",default:!1}),Oi=(e,t,n,i,s)=>zod.z.object({temperature:Pi(e,t).schema,maxTokens:Mi(n).schema,stop:vi(i).schema,topP:ki(s).schema,toolChoice:_i.schema,safetySettings:xi.schema,googleSearchTool:wi.schema}),Gi=(e,t,n,i,s)=>({temperature:Pi(e,t).def,maxTokens:Mi(n).def,stop:vi(i).def,topP:ki(s).def,toolChoice:_i.def,safetySettings:xi.def,googleSearchTool:wi.def}),Ri=ei({param:"response_schema",title:G.RESPONSE_SCHEMA.title,description:G.RESPONSE_SCHEMA.description,objectSchema:_n}),Ii=Le({param:"response_format",title:G.RESPONSE_FORMAT_WITH_SCHEMA.title,description:G.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_schema"]}),ji=(e,t,n,i,s)=>he(S({},Gi(e,t,n,i,s)),{responseFormat:Ii.def,responseSchema:Ri.def}),Fi=(e,t,n,i,s)=>Oi(e,t,n,i,s).extend({responseFormat:Ii.schema,responseSchema:Ri.schema}),Mr=(e,t,n,i,s,m,r)=>Fi(e,t,n,i,s).extend({reasoningEnabled:Si.schema,maxReasoningTokens:Ei(m,r).schema,reasoningEffort:Ci.schema}),vr=(e,t,n,i,s,m,r)=>he(S({},ji(e,t,n,i,s)),{reasoningEnabled:Si.def,maxReasoningTokens:Ei(m,r).def,reasoningEffort:Ci.def}),Li=e=>W({param:"outputDimensionality",title:_e.DIMENSIONS.title,description:_e.DIMENSIONS.description,min:1,max:e,step:1,default:e}),kr=e=>zod.z.object({dimensions:Li(e).schema}),_r=e=>({dimensions:Li(e).def}),k={base:(e,t,n,i,s)=>({def:Gi(e,t,n,i,s),schema:Oi(e,t,n,i,s)}),responseSchema:(e,t,n,i,s)=>({def:ji(e,t,n,i,s),schema:Fi(e,t,n,i,s)}),reasoning:(e,t,n,i,s,m,r)=>({def:vr(e,t,n,i,s,m,r),schema:Mr(e,t,n,i,s,m,r)})},Ue={base:e=>({def:_r(e),schema:kr(e)})},xr="google",co=class{constructor(){this.version="v1",this.name=xr,this.chatModelFactories={[Yt]:{model:Wr,modelOptions:Yr,modelSchema:De},[Wt]:{model:Zr,modelOptions:Xr,modelSchema:$e},[Jt]:{model:tl,modelOptions:el,modelSchema:Be},[Xt]:{model:il,modelOptions:nl,modelSchema:Ae},[Zt]:{model:rl,modelOptions:sl,modelSchema:qe},[Qt]:{model:dl,modelOptions:ml,modelSchema:ze},[eo]:{model:ul,modelOptions:pl,modelSchema:He},[to]:{model:fl,modelOptions:hl,modelSchema:Ve},[oo]:{model:Pl,modelOptions:Tl,modelSchema:Ke},[io]:{model:Sl,modelOptions:xl,modelSchema:We},[so]:{model:Rl,modelOptions:Gl,modelSchema:Xe},[ao]:{model:wl,modelOptions:Cl,modelSchema:Je},[ro]:{model:Fl,modelOptions:jl,modelSchema:Ze},[lo]:{model:Ul,modelOptions:Nl,modelSchema:Qe},[mo]:{model:Bl,modelOptions:$l,modelSchema:et},[no]:{model:kl,modelOptions:vl,modelSchema:Ye}},this.embeddingModelFactories={[qi]:{model:Kl,modelOptions:Vl,modelSchema:zi},[Hi]:{model:Jl,modelOptions:Wl,modelSchema:Vi}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}chatModel(e){let t=e.modelName;if(!(t in this.chatModelFactories))throw new ve({info:`Google chat model: ${t} not found`,cause:new Error(`Google chat model: ${t} not found, available chat models:
8
8
  [${this.chatModelLiterals().join(", ")}]`)});let n=this.chatModelFactories[t].model,i=this.chatModelFactories[t].modelOptions.parse(e);return new n(i)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,t)=>(e[t]=this.embeddingModelFactories[t].modelSchema,e),{})}embeddingModel(e){let t=e.modelName;if(!(t in this.embeddingModelFactories))throw new ve({info:`Google embedding model: ${t} not found`,cause:new Error(`Google embedding model: ${t} not found, available embedding models:
9
- [${this.embeddingModelLiterals().join(", ")}]`)});let n=this.embeddingModelFactories[t].model,i=this.embeddingModelFactories[t].modelOptions.parse(e);return new n(i)}};co.baseUrl="https://generativelanguage.googleapis.com/v1beta";var R={"base-gemini-1-chat-model":{modelName:"base-gemini-1-chat-model",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:0,outputPricePerMillion:0}}}]},"gemini-1.0-pro-001":{modelName:"gemini-1.0-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro-latest":{modelName:"gemini-1.0-pro-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro-vision":{modelName:"gemini-1.0-pro-vision",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro":{modelName:"gemini-1.0-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.5-flash-001":{modelName:"gemini-1.5-flash-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-flash-002":{modelName:"gemini-1.5-flash-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.0375,outputPricePerMillion:.15}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}}]},"gemini-1.5-flash-latest":{modelName:"gemini-1.5-flash-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-flash":{modelName:"gemini-1.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-pro-001":{modelName:"gemini-1.5-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro-002":{modelName:"gemini-1.5-pro-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro-latest":{modelName:"gemini-1.5-pro-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro":{modelName:"gemini-1.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-2.0-flash-exp":{modelName:"gemini-2.0-flash-exp",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-2.5-flash-preview-04-17":{modelName:"gemini-2.5-flash-preview-04-17",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-2.5-pro-preview-03-25":{modelName:"gemini-2.5-pro-preview-03-25",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:15}}}]},"gemini-pro-vision":{modelName:"gemini-pro-vision",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-pro":{modelName:"gemini-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-2.5-pro":{modelName:"gemini-2.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gemini-3-pro-preview":{modelName:"gemini-3-pro-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gemini-2.5-flash":{modelName:"gemini-2.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.3,outputPricePerMillion:2.5}}}]},"gemini-2.0-flash":{modelName:"gemini-2.0-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-2.5-flash-lite":{modelName:"gemini-2.5-flash-lite",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-3-flash-preview":{modelName:"gemini-3-flash-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:3}}}]}},L=zod.z.enum([Ee,Q,E,re]),Sr="model",Er="function",N={system:Q,user:Q,assistant:Sr,tool:Er},U=[B,le,ue,Y,me,ge,Te,be],D=zod.z.enum([B,le,ue,Y,me,ge,Te,be]);zod.z.enum([B]);zod.z.enum([B,le]);zod.z.enum([B,Y,me]);var Cr=zod.z.object({renderedContent:zod.z.string().optional()}),wr=zod.z.object({uri:zod.z.string().optional(),title:zod.z.string().optional()}),Gr=zod.z.object({web:wr.optional()}),Or=zod.z.object({startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),text:zod.z.string().optional()}),Rr=zod.z.object({segment:Or.optional(),groundingChunkIndices:zod.z.array(zod.z.number()).optional(),confidenceScores:zod.z.array(zod.z.number()).optional()}),Ni=zod.z.object({searchEntryPoint:Cr.optional(),groundingChunks:zod.z.array(Gr).optional(),groundingSupports:zod.z.array(Rr).optional(),webSearchQueries:zod.z.array(zod.z.string()).optional()}),Ir=zod.z.object({text:zod.z.string(),thought:zod.z.boolean().optional()}),jr=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),Fr=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([Ir,jr]))}).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()}))),groundingMetadata:Ni.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()}),Lr=zod.z.object({text:zod.z.string(),thought:zod.z.boolean().optional()}),Nr=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),ci=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([Lr,Nr]))}).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()}))),groundingMetadata:Ni.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().optional(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number().optional()}).optional()}),Ui=zod.z.object({text:zod.z.string().min(1)}),Ur=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),Dr=zod.z.object({file_data:zod.z.object({mime_type:zod.z.string().min(1),file_uri:zod.z.string().min(1)})}),$r=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))})}),Br=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),pi=zod.z.object({text:zod.z.string(),thought:zod.z.literal(!0),thought_signature:zod.z.string().min(1)}),Ar=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([Ui,Ur,Dr,$r,Br,pi,pi]))}),ui=zod.z.object({parts:zod.z.array(Ui)}),qr=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),Hr=zod.z.object({timeRangeFilter:zod.z.object({startTime:zod.z.string().datetime().optional(),endTime:zod.z.string().datetime().optional()}).optional()}),gi=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()})}),zr=zod.z.object({thinkingBudget:zod.z.number().optional(),includeThoughts:zod.z.boolean().optional(),thinkingLevel:zod.z.enum(["LOW","HIGH"]).optional()}),hi=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(),thinkingConfig:zr.optional()}),fi=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"])}),Vr=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(Ar),systemInstruction:ui.optional(),system_instruction:ui.optional(),generationConfig:hi.optional(),generation_config:hi.optional(),safetySettings:zod.z.array(fi).optional(),safety_settings:zod.z.array(fi).optional(),tools:zod.z.object({function_declarations:zod.z.array(qr),google_search:Hr.optional()}).optional(),toolConfig:gi.optional(),tool_config:gi.optional()}),$=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()}),F=class{constructor(e,t){this.version="v1";var n;let i=$.parse(t);this.modelSchema=e,this.modelName=i.modelName,this.apiKey=i.apiKey,this.baseUrl=xe((n=i.baseUrl)!=null?n:co.baseUrl),this.completeChatUrl=xe(i.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=xe(i.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.reduce((t,n)=>t+n.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformPdfMessages(e){return j(this,null,function*(){let t=r=>j(this,null,function*(){let d={};Kt()||(d["User-Agent"]="Mozilla/5.0 (compatible; GoogleFilesAPI/1.0)");let l=yield fetch(r,{headers:d});if(!l.ok)throw new C({info:`Failed to download PDF from URL: ${r}`,cause:new Error(`HTTP ${l.status}: ${l.statusText}`)});let p=yield l.arrayBuffer();return new Uint8Array(p)}),n=r=>j(this,null,function*(){try{let d=yield fetch(`https://generativelanguage.googleapis.com/v1beta/files?key=${this.apiKey}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!d.ok)return null;let l=((yield d.json()).files||[]).find(p=>p.displayName===r);return l?l.uri:null}catch(d){return null}}),i=(r,d)=>j(this,null,function*(){let l=yield fetch(`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.apiKey}`,{method:"POST",headers:{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":r.length.toString(),"X-Goog-Upload-Header-Content-Type":"application/pdf","Content-Type":"application/json"},body:JSON.stringify({file:{display_name:d}})});if(!l.ok)throw new C({info:"Failed to start PDF upload to Google Files API",cause:new Error(`HTTP ${l.status}: ${l.statusText}`)});let p=l.headers.get("x-goog-upload-url");if(!p)throw new C({info:"No upload URL received from Google Files API",cause:new Error("Missing x-goog-upload-url header")});let h={"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"};Kt()||(h["Content-Length"]=r.length.toString());let y=yield fetch(p,{method:"POST",headers:h,body:r});if(!y.ok)throw new C({info:"Failed to upload PDF content to Google Files API",cause:new Error(`HTTP ${y.status}: ${y.statusText}`)});return (yield y.json()).file.uri}),s=r=>j(this,null,function*(){let d=yield n(r.file.id);if(d)return d;let l;if(r.value.type==="url")l=yield t(r.value.url);else {let p=r.value.base64,h="data:application/pdf;base64,";p=p.startsWith(h)?p.substring(h.length):p,l=ri(p);}return yield i(l,r.file.id)}),m=[];for(let r of e){let d=[];for(let l of r.content)if(l.modality===ue){let p=yield s(l);d.push(he(S({},l),{value:{type:"url",url:p}}));}else d.push(l);m.push(he(S({},r),{content:d}));}return m})}transformModelRequest(e){let t=Vr.safeParse(e);if(!t.success)throw new ie({info:"Invalid model request",cause:t.error});let n=t.data,i=n.model;if(n.system_instruction&&n.systemInstruction)throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'system_instruction' and 'systemInstruction' are not allowed at the same time")});if(n.generation_config&&n.generationConfig)throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'generation_config' and 'generationConfig' are not allowed at the same time")});if(n.tool_config&&n.toolConfig)throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let s=n.system_instruction||n.systemInstruction,m=n.generation_config||n.generationConfig,r=n.safety_settings||n.safetySettings,d=n.tool_config||n.toolConfig;if(d&&(!n.tools||n.tools.function_declarations.length===0))throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let l={};d&&(d.function_calling_config.mode==="ANY"&&d.function_calling_config.allowed_function_names&&d.function_calling_config.allowed_function_names.length===1?l.toolChoice=d.function_calling_config.allowed_function_names[0]:l.toolChoice=d.function_calling_config.mode.toLowerCase()),l.seed=m==null?void 0:m.seed,l.maxTokens=m==null?void 0:m.maxOutputTokens,l.temperature=m==null?void 0:m.temperature,l.topP=m==null?void 0:m.topP,l.presencePenalty=m==null?void 0:m.presencePenalty,l.frequencyPenalty=m==null?void 0:m.frequencyPenalty,l.stop=m==null?void 0:m.stopSequences,l.safetySettings=r;let p=Ce().parse(Oe(l)),h=[];s&&s.parts.forEach(u=>{h.push({role:Ee,content:[{modality:B,value:u.text}]});}),n.contents.forEach(u=>{let g=u.role;switch(g){case"user":{let f=u.parts.map(_=>"text"in _?{modality:B,value:_.text}:{modality:le,detail:"auto",value:{type:Et,base64:_.inline_data.data,mediaType:_.inline_data.mime_type.split("/")[1]}});h.push({role:g,content:f});}break;case"model":{let f=u.parts.map((_,w)=>"text"in _?{modality:B,value:_.text}:{modality:Y,id:w.toString(),index:w,name:_.function_call.name,arguments:JSON.stringify(_.function_call.args)});h.push({role:E,content:f});}break;case"function":{let f=u.parts.map((_,w)=>({modality:me,id:w.toString(),index:w,name:_.function_response.name,data:JSON.stringify(_.function_response.response)}));h.push({role:re,content:f});}break;default:throw new C({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${u.role}' is not supported for model : ${this.modelName}`)})}});let y=[];return n.tools&&n.tools.function_declarations.forEach(u=>{y.push({type:"function",definition:{schema:{name:u.name,description:u.description,parameters:u.parameters}}});}),{modelName:i,config:p,messages:h,tools:y.length>0?y:void 0}}transformConfig(e,t,n){let i=e.toolChoice;delete e.toolChoice;let s=this.modelSchema.config.schema.safeParse(e);if(!s.success)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:s.error});let m=s.data;Object.keys(m).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${p}',
9
+ [${this.embeddingModelLiterals().join(", ")}]`)});let n=this.embeddingModelFactories[t].model,i=this.embeddingModelFactories[t].modelOptions.parse(e);return new n(i)}};co.baseUrl="https://generativelanguage.googleapis.com/v1beta";var R={"base-gemini-1-chat-model":{modelName:"base-gemini-1-chat-model",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:0,outputPricePerMillion:0}}}]},"gemini-1.0-pro-001":{modelName:"gemini-1.0-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro-latest":{modelName:"gemini-1.0-pro-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro-vision":{modelName:"gemini-1.0-pro-vision",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro":{modelName:"gemini-1.0-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.5-flash-001":{modelName:"gemini-1.5-flash-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-flash-002":{modelName:"gemini-1.5-flash-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.0375,outputPricePerMillion:.15}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}}]},"gemini-1.5-flash-latest":{modelName:"gemini-1.5-flash-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-flash":{modelName:"gemini-1.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-pro-001":{modelName:"gemini-1.5-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro-002":{modelName:"gemini-1.5-pro-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro-latest":{modelName:"gemini-1.5-pro-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro":{modelName:"gemini-1.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-2.0-flash-exp":{modelName:"gemini-2.0-flash-exp",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-2.5-flash-preview-04-17":{modelName:"gemini-2.5-flash-preview-04-17",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-2.5-pro-preview-03-25":{modelName:"gemini-2.5-pro-preview-03-25",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:15}}}]},"gemini-pro-vision":{modelName:"gemini-pro-vision",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-pro":{modelName:"gemini-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-2.5-pro":{modelName:"gemini-2.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gemini-3-pro-preview":{modelName:"gemini-3-pro-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}}]},"gemini-2.5-flash":{modelName:"gemini-2.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.3,outputPricePerMillion:2.5}}}]},"gemini-2.0-flash":{modelName:"gemini-2.0-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-2.5-flash-lite":{modelName:"gemini-2.5-flash-lite",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-3-flash-preview":{modelName:"gemini-3-flash-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:3}}}]}},L=zod.z.enum([Ee,Q,E,re]),Sr="model",Er="function",N={system:Q,user:Q,assistant:Sr,tool:Er},U=[B,le,ue,Y,me,ge,Te,be],D=zod.z.enum([B,le,ue,Y,me,ge,Te,be]);zod.z.enum([B]);zod.z.enum([B,le]);zod.z.enum([B,Y,me]);var Cr=zod.z.object({renderedContent:zod.z.string().optional()}),wr=zod.z.object({uri:zod.z.string().optional(),title:zod.z.string().optional()}),Or=zod.z.object({web:wr.optional()}),Gr=zod.z.object({startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),text:zod.z.string().optional()}),Rr=zod.z.object({segment:Gr.optional(),groundingChunkIndices:zod.z.array(zod.z.number()).optional(),confidenceScores:zod.z.array(zod.z.number()).optional()}),Ni=zod.z.object({searchEntryPoint:Cr.optional(),groundingChunks:zod.z.array(Or).optional(),groundingSupports:zod.z.array(Rr).optional(),webSearchQueries:zod.z.array(zod.z.string()).optional()}),Ir=zod.z.object({text:zod.z.string(),thought:zod.z.boolean().optional()}),jr=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())}),thoughtSignature:zod.z.string().optional()}),Fr=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([Ir,jr]))}).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()}))),groundingMetadata:Ni.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()}),Lr=zod.z.object({text:zod.z.string(),thought:zod.z.boolean().optional()}),Nr=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())}),thoughtSignature:zod.z.string().optional()}),ci=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([Lr,Nr]))}).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()}))),groundingMetadata:Ni.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().optional(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number().optional()}).optional()}),Ui=zod.z.object({text:zod.z.string().min(1)}),Ur=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),Dr=zod.z.object({file_data:zod.z.object({mime_type:zod.z.string().min(1),file_uri:zod.z.string().min(1)})}),$r=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))}),thought_signature:zod.z.string().optional()}),Br=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),pi=zod.z.object({text:zod.z.string(),thought:zod.z.literal(!0),thought_signature:zod.z.string().min(1)}),Ar=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([Ui,Ur,Dr,$r,Br,pi,pi]))}),ui=zod.z.object({parts:zod.z.array(Ui)}),qr=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),zr=zod.z.object({timeRangeFilter:zod.z.object({startTime:zod.z.string().datetime().optional(),endTime:zod.z.string().datetime().optional()}).optional()}),gi=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()})}),Hr=zod.z.object({thinkingBudget:zod.z.number().optional(),includeThoughts:zod.z.boolean().optional(),thinkingLevel:zod.z.enum(["LOW","HIGH"]).optional()}),hi=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(),thinkingConfig:Hr.optional()}),fi=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"])}),Vr=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(Ar),systemInstruction:ui.optional(),system_instruction:ui.optional(),generationConfig:hi.optional(),generation_config:hi.optional(),safetySettings:zod.z.array(fi).optional(),safety_settings:zod.z.array(fi).optional(),tools:zod.z.object({function_declarations:zod.z.array(qr),google_search:zr.optional()}).optional(),toolConfig:gi.optional(),tool_config:gi.optional()}),$=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()}),F=class{constructor(e,t){this.version="v1";var n;let i=$.parse(t);this.modelSchema=e,this.modelName=i.modelName,this.apiKey=i.apiKey,this.baseUrl=xe((n=i.baseUrl)!=null?n:co.baseUrl),this.completeChatUrl=xe(i.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=xe(i.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.reduce((t,n)=>t+n.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformPdfMessages(e){return j(this,null,function*(){let t=r=>j(this,null,function*(){let d={};Kt()||(d["User-Agent"]="Mozilla/5.0 (compatible; GoogleFilesAPI/1.0)");let l=yield fetch(r,{headers:d});if(!l.ok)throw new C({info:`Failed to download PDF from URL: ${r}`,cause:new Error(`HTTP ${l.status}: ${l.statusText}`)});let p=yield l.arrayBuffer();return new Uint8Array(p)}),n=r=>j(this,null,function*(){try{let d=yield fetch(`https://generativelanguage.googleapis.com/v1beta/files?key=${this.apiKey}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!d.ok)return null;let l=((yield d.json()).files||[]).find(p=>p.displayName===r);return l?l.uri:null}catch(d){return null}}),i=(r,d)=>j(this,null,function*(){let l=yield fetch(`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.apiKey}`,{method:"POST",headers:{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":r.length.toString(),"X-Goog-Upload-Header-Content-Type":"application/pdf","Content-Type":"application/json"},body:JSON.stringify({file:{display_name:d}})});if(!l.ok)throw new C({info:"Failed to start PDF upload to Google Files API",cause:new Error(`HTTP ${l.status}: ${l.statusText}`)});let p=l.headers.get("x-goog-upload-url");if(!p)throw new C({info:"No upload URL received from Google Files API",cause:new Error("Missing x-goog-upload-url header")});let h={"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"};Kt()||(h["Content-Length"]=r.length.toString());let y=yield fetch(p,{method:"POST",headers:h,body:r});if(!y.ok)throw new C({info:"Failed to upload PDF content to Google Files API",cause:new Error(`HTTP ${y.status}: ${y.statusText}`)});return (yield y.json()).file.uri}),s=r=>j(this,null,function*(){let d=yield n(r.file.id);if(d)return d;let l;if(r.value.type==="url")l=yield t(r.value.url);else {let p=r.value.base64,h="data:application/pdf;base64,";p=p.startsWith(h)?p.substring(h.length):p,l=ri(p);}return yield i(l,r.file.id)}),m=[];for(let r of e){let d=[];for(let l of r.content)if(l.modality===ue){let p=yield s(l);d.push(he(S({},l),{value:{type:"url",url:p}}));}else d.push(l);m.push(he(S({},r),{content:d}));}return m})}transformModelRequest(e){let t=Vr.safeParse(e);if(!t.success)throw new ie({info:"Invalid model request",cause:t.error});let n=t.data,i=n.model;if(n.system_instruction&&n.systemInstruction)throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'system_instruction' and 'systemInstruction' are not allowed at the same time")});if(n.generation_config&&n.generationConfig)throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'generation_config' and 'generationConfig' are not allowed at the same time")});if(n.tool_config&&n.toolConfig)throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let s=n.system_instruction||n.systemInstruction,m=n.generation_config||n.generationConfig,r=n.safety_settings||n.safetySettings,d=n.tool_config||n.toolConfig;if(d&&(!n.tools||n.tools.function_declarations.length===0))throw new ie({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let l={};d&&(d.function_calling_config.mode==="ANY"&&d.function_calling_config.allowed_function_names&&d.function_calling_config.allowed_function_names.length===1?l.toolChoice=d.function_calling_config.allowed_function_names[0]:l.toolChoice=d.function_calling_config.mode.toLowerCase()),l.seed=m==null?void 0:m.seed,l.maxTokens=m==null?void 0:m.maxOutputTokens,l.temperature=m==null?void 0:m.temperature,l.topP=m==null?void 0:m.topP,l.presencePenalty=m==null?void 0:m.presencePenalty,l.frequencyPenalty=m==null?void 0:m.frequencyPenalty,l.stop=m==null?void 0:m.stopSequences,l.safetySettings=r;let p=Ce().parse(Ge(l)),h=[];s&&s.parts.forEach(u=>{h.push({role:Ee,content:[{modality:B,value:u.text}]});}),n.contents.forEach(u=>{let g=u.role;switch(g){case"user":{let f=u.parts.map(_=>"text"in _?{modality:B,value:_.text}:{modality:le,detail:"auto",value:{type:Et,base64:_.inline_data.data,mediaType:_.inline_data.mime_type.split("/")[1]}});h.push({role:g,content:f});}break;case"model":{let f=u.parts.map((_,w)=>"text"in _?{modality:B,value:_.text}:{modality:Y,id:w.toString(),index:w,name:_.function_call.name,arguments:JSON.stringify(_.function_call.args)});h.push({role:E,content:f});}break;case"function":{let f=u.parts.map((_,w)=>({modality:me,id:w.toString(),index:w,name:_.function_response.name,data:JSON.stringify(_.function_response.response)}));h.push({role:re,content:f});}break;default:throw new C({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${u.role}' is not supported for model : ${this.modelName}`)})}});let y=[];return n.tools&&n.tools.function_declarations.forEach(u=>{y.push({type:"function",definition:{schema:{name:u.name,description:u.description,parameters:u.parameters}}});}),{modelName:i,config:p,messages:h,tools:y.length>0?y:void 0}}transformConfig(e,t,n){let i=e.toolChoice;delete e.toolChoice;let s=this.modelSchema.config.schema.safeParse(e);if(!s.success)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:s.error});let m=s.data;Object.keys(m).forEach(p=>{if(!(p in this.modelSchema.config.def))throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${p}',
10
10
  available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let r=Object.keys(m).reduce((p,h)=>{let y=this.modelSchema.config.def[h],u=y.param,g=m[h];return h==="reasoningEnabled"?p.thinkingConfig=p.thinkingConfig&&typeof p.thinkingConfig=="object"?he(S({},p.thinkingConfig),{includeThoughts:g}):{includeThoughts:g}:h==="maxReasoningTokens"?p.thinkingConfig=p.thinkingConfig&&typeof p.thinkingConfig=="object"?he(S({},p.thinkingConfig),{thinkingBudget:g}):{thinkingBudget:g}:h==="reasoningEffort"?p.thinkingConfig=p.thinkingConfig&&typeof p.thinkingConfig=="object"?he(S({},p.thinkingConfig),{thinkingLevel:g}):{thinkingLevel:g}:u==="maxOutputTokens"&&y.type==="range"&&g===0?p[u]=y.max:p[u]=g,p},{});if(r.thinkingConfig&&typeof r.thinkingConfig=="object"&&"thinkingBudget"in r.thinkingConfig&&"thinkingLevel"in r.thinkingConfig&&r.thinkingConfig.thinkingBudget!==void 0&&r.thinkingConfig.thinkingBudget!==0&&r.thinkingConfig.thinkingLevel!==void 0)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("Only one of 'thinkingBudget' or 'thinkingLevel' can be set, not both.")});let d=r.safetySettings;delete r.safetySettings,delete r.googleSearch;let l;if(i!==void 0){let p=i;if(!n||n&&n.length===0)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(n&&n.length>0){let h=this.modelSchema.config.def.toolChoice;if(h.choices.includes(p))p==="any"?l={function_calling_config:{mode:"ANY",allowed_function_names:n.map(y=>y.definition.schema.name)}}:l={function_calling_config:{mode:p.toUpperCase()}};else if(n.map(y=>y.definition.schema.name).includes(p))l={function_calling_config:{mode:"ANY",allowed_function_names:[p]}};else throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${p}' is not part of provided 'tools' names or
11
11
  one of [${h.choices.join(", ")}]`)})}}if("response_format"in r&&r.response_format!==void 0){let p=r.response_format;if(p==="json_schema"){let h=r.response_schema;if(!("response_schema"in r)||!r.response_schema||!(h!=null&&h.schema))throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});r.responseSchema=h.schema,r.responseMimeType="application/json","additionalProperties"in h.schema&&delete r.responseSchema.additionalProperties,delete r.response_format,delete r.response_schema;}else p==="json_object"?(r.responseSchema={type:"object"},delete r.response_format):p==="text"&&delete r.response_format;}return S(S({generation_config:r},l?{tool_config:l}:{}),d?{safety_settings:d}:{})}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=r=>{let d=r.match(/^data:(image\/[a-zA-Z]+|application\/pdf);base64,/);return d?r.substring(d[0].length):r},n=e.map(r=>{let d=Rt().safeParse(r);if(!d.success)throw new C({info:"Invalid messages",cause:d.error});return d.data});n.forEach(r=>{r.content.forEach(d=>{if(!this.modelSchema.modalities.includes(d.modality))throw new C({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${d.modality}',
12
12
  available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),n.forEach(r=>{if(!Object.keys(this.modelSchema.roles).includes(r.role))throw new C({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${r.role}',
13
- available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),n.forEach(r=>{r.content=r.content.filter(d=>d.modality!=="error"&&d.modality!=="search-result");});let i={parts:[]},s=[];if(n.forEach(r=>{switch(r.role){case Ee:r.content.forEach(d=>{if(d.modality===B)i.parts.push({text:d.value});else throw new C({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 E:{let d=[];r.content.forEach(l=>{if(l.modality===B)d.push({text:l.value});else if(l.modality===Y)d.push({function_call:{name:l.name,args:JSON.parse(l.arguments)}});else if(l.modality===ge)l.value.type==="thinking"&&l.value.thinking&&d.push({text:l.value.thinking,thought:!0,thought_signature:l.value.signature});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[r.role],parts:d});}break;case Q:{let d=[];r.content.forEach(l=>{if(l.modality===B)d.push({text:l.value});else if(l.modality===le){if(l.value.type==="base64"){let p=l.value.base64;p=t(p),d.push({inline_data:{mime_type:`image/${l.value.mediaType}`,data:p}});}else if(l.value.type==="url")throw new C({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${l.value.type}'`)})}else if(l.modality===ue)if(l.value.type==="base64"){let p=l.value.base64;p=t(p),d.push({inline_data:{mime_type:"application/pdf",data:p}});}else l.value.type==="url"&&d.push({file_data:{mime_type:"application/pdf",file_uri:l.value.url}});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[r.role],parts:d});}break;case re:{let d=[];r.content.forEach(l=>{if(l.modality===me)d.push({function_response:{name:l.name,response:JSON.parse(l.data)}});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[r.role],parts:d});}break;default:throw new C({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' is not supported,
14
- available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),s[0].role!==this.modelSchema.roles[Q])throw new C({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});let m=r=>r===this.modelSchema.roles[Q]||r===this.modelSchema.roles[re]?[this.modelSchema.roles[E]]:[this.modelSchema.roles[Q],this.modelSchema.roles[re]];for(let r=1;r<s.length;r++)if(!m(s[r-1].role).includes(s[r].role))throw new C({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${s[r].role}' after message with role : '${s[r-1].role}'`)});if(s[s.length-1].role!==this.modelSchema.roles[Q]&&s[s.length-1].role!==this.modelSchema.roles[re])throw new C({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires last message to be from user`)});return S({contents:s},i.parts.length>0?{system_instruction:i}:{})}stripAdditionalProperties(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.stripAdditionalProperties(n));let t={};for(let[n,i]of Object.entries(e))n!=="additionalProperties"&&(t[n]=this.stripAdditionalProperties(i));return t}transformTools(e,t){if(!this.modelSchema.modalities.includes(Y))throw new $t({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${Y}'`)});if((!e||e.length===0)&&!(t!=null&&t.googleSearchTool))return {tools:[]};let n=(e!=null?e:[]).map(i=>{let s=Cn().safeParse(i);if(!s.success)throw new $t({info:"Invalid tools",cause:s.error});return s.data}).map(i=>({name:i.definition.schema.name,description:i.definition.schema.description,parameters:this.stripAdditionalProperties(i.definition.schema.parameters)}));return {tools:[S(S({},n.length>0?{function_declarations:n}:{}),t!=null&&t.googleSearchTool?{google_search:{}}:{})]}}getCompleteChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getCompleteChatData(e,t,n){return j(this,null,function*(){let i=this.transformConfig(e,t,n),s=yield this.transformPdfMessages(t),m=this.transformMessages(s);if(m.messages&&m.messages.length===0)throw new C({info:"Messages are required",cause:new Error("Messages are required")});let r=this.transformTools(n||[],e);return S(S(S(S({},this.getDefaultParams()),i),m),r)})}transformCompleteChatResponse(e){var t,n,i,s,m,r;let d=Fr.safeParse(e);if(d.success){if(d.data.candidates.length===0)throw new H({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(d.data)}`)});let l={messages:[],usage:void 0,logProbs:void 0},p=d.data;p.usageMetadata&&(l.usage={promptTokens:p.usageMetadata.promptTokenCount,totalTokens:p.usageMetadata.totalTokenCount,completionTokens:p.usageMetadata.candidatesTokenCount||0});let h=p.candidates[0];if(h.content){let u=h.content.parts.map((g,f)=>{if("text"in g&&g.text!==void 0)return g.thought===!0?On(g.text,""):wn(g.text);if("functionCall"in g&&g.functionCall!==void 0)return Gn(f,`${g.functionCall.name}_${f}`,g.functionCall.name,JSON.stringify(g.functionCall.args))});l.messages.push({role:E,content:u});}h.groundingMetadata&&(l.messages.length===0?l.messages.push({role:E,content:[Ut(((t=h.groundingMetadata.webSearchQueries)==null?void 0:t[0])||"",((n=h.groundingMetadata.groundingChunks)==null?void 0:n.map(u=>{var g,f;return {source:u.web?"web":"",url:((g=u.web)==null?void 0:g.uri)||"",title:((f=u.web)==null?void 0:f.title)||""}}))||[],((i=h.groundingMetadata.groundingSupports)==null?void 0:i.map(u=>{var g,f,_;return {text:((g=u.segment)==null?void 0:g.text)||"",responseIndices:u.groundingChunkIndices||[],startIndex:((f=u.segment)==null?void 0:f.startIndex)||void 0,endIndex:((_=u.segment)==null?void 0:_.endIndex)||void 0,confidenceScores:u.confidenceScores||void 0}}))||[])]}):l.messages[0].content.push(Ut(((s=h.groundingMetadata.webSearchQueries)==null?void 0:s[0])||"",((m=h.groundingMetadata.groundingChunks)==null?void 0:m.map(u=>{var g,f;return {source:u.web?"web":"",url:((g=u.web)==null?void 0:g.uri)||"",title:((f=u.web)==null?void 0:f.title)||""}}))||[],((r=h.groundingMetadata.groundingSupports)==null?void 0:r.map(u=>{var g,f,_;return {text:((g=u.segment)==null?void 0:g.text)||"",responseIndices:u.groundingChunkIndices||[],startIndex:((f=u.segment)==null?void 0:f.startIndex)||void 0,endIndex:((_=u.segment)==null?void 0:_.endIndex)||void 0,confidenceScores:u.confidenceScores||void 0}}))||[])));let y=h.safetyRatings;if(y&&y.length>0&&y.forEach(u=>{u.blocked&&(l.messages.length===0?l.messages.push({role:E,content:[Lt(u.category,u.probability,u.blocked,`Blocked content for category: ${u.category} with probability: ${u.probability}`)]}):l.messages[0].content.push(Lt(u.category,u.probability,u.blocked,`Blocked content for category: ${u.category} with probability: ${u.probability}`)));}),l.messages.length>0)return l;if(l.messages.length===0&&h.finishReason==="SAFETY")throw new H({info:"Blocked content, model response finished with safety reason",cause:new Error("Blocked content, model response finished with safety reason")})}throw new H({info:"Invalid response from model",cause:d.error})}getStreamChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.streamChatUrl);})})}getStreamChatHeaders(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getStreamChatData(e,t,n){return j(this,null,function*(){let i=this.transformConfig(e,t,n),s=yield this.transformPdfMessages(t),m=this.transformMessages(s);if(m.messages&&m.messages.length===0)throw new C({info:"Messages are required",cause:new Error("Messages are required")});let r=this.transformTools(n||[],e);return S(S(S(S({},this.getDefaultParams()),i),m),r)})}transformStreamChatResponseChunk(e,t){return di(this,null,function*(){var n,i,s;let m=(t+e).split(",\r").filter(r=>r.trim()!=="");for(let r of m){let d=r;if(d=d.replace(/\n/g,""),d.startsWith("[")||d.startsWith(",{"))d=d.slice(1);else if(d.endsWith("]")){if(d==="]")return;d=d.slice(0,-1);}let l;try{l=JSON.parse(d);}catch(h){if(h instanceof SyntaxError){t=d;continue}else throw h}t="";let p=ci.safeParse(l);if(p.success){let h={partialMessages:[]},y=p.data;if(y.candidates.length>0){let u=y.candidates[0].content;u&&"parts"in u&&u.parts.length>0&&u.parts.forEach((g,f)=>{if("text"in g&&g.text!==void 0&&(g.thought===!0?h.partialMessages.push(Ft(E,g.text,"")):h.partialMessages.push(It(E,g.text))),"functionCall"in g&&g.functionCall!==void 0){let _=g.functionCall;h.partialMessages.push(jt(E,f,`${_.name}_${f}`,_.name,JSON.stringify(_.args)));}});}if(y.usageMetadata&&(h.usage={promptTokens:y.usageMetadata.promptTokenCount,completionTokens:y.usageMetadata.candidatesTokenCount,totalTokens:y.usageMetadata.totalTokenCount}),y.candidates.length>0){let u=y.candidates[0];u.groundingMetadata&&h.partialMessages.push(Dt(E,((n=u.groundingMetadata.webSearchQueries)==null?void 0:n[0])||"",((i=u.groundingMetadata.groundingChunks)==null?void 0:i.map(f=>{var _,w;return {source:f.web?"web":"",url:((_=f.web)==null?void 0:_.uri)||"",title:((w=f.web)==null?void 0:w.title)||""}}))||[],((s=u.groundingMetadata.groundingSupports)==null?void 0:s.map(f=>{var _,w,q;return {text:((_=f.segment)==null?void 0:_.text)||"",responseIndices:f.groundingChunkIndices||[],startIndex:((w=f.segment)==null?void 0:w.startIndex)||void 0,endIndex:((q=f.segment)==null?void 0:q.endIndex)||void 0,confidenceScores:f.confidenceScores||void 0}}))||[]));let g=u.safetyRatings;g&&g.length>0&&g.forEach(f=>{f.blocked&&h.partialMessages.push(Nt(E,f.category,f.probability,f.blocked,`Blocked content for category: ${f.category} with probability: ${f.probability}`));});}yield {partialResponse:h,buffer:t};}else throw new H({info:"Invalid response from model",cause:p.error})}yield {partialResponse:{partialMessages:[]},buffer:t};})}transformProxyStreamChatResponseChunk(e,t,n,i,s){return di(this,null,function*(){var m,r,d;if((s==null?void 0:s.alt)!=="sse"){yield*rn(fr(this.transformStreamChatResponseChunk(e,t)));return}let l=t+e,p=[],h="",y=0;for(;y<l.length;){let u=l.indexOf(`
15
- `,y);if(u===-1){h=l.substring(y);break}else {let g=l.substring(y,u).trim();g&&p.push(g),y=u+1;}}for(let u of p){if(u==="data: [DONE]")return;if(u.startsWith("data: ")){let g=u.substring(6);try{let f=JSON.parse(g),_=ci.safeParse(f);if(_.success){let w={partialMessages:[]},q=_.data;if(q.candidates.length>0){let X=q.candidates[0].content;X&&"parts"in X&&X.parts.length>0&&X.parts.forEach((z,G)=>{if("text"in z&&z.text!==void 0&&(z.thought===!0?w.partialMessages.push(Ft(E,z.text,"")):w.partialMessages.push(It(E,z.text))),"functionCall"in z&&z.functionCall!==void 0){let oe=z.functionCall;w.partialMessages.push(jt(E,G,`${oe.name}_${G}`,oe.name,JSON.stringify(oe.args)));}});}if(q.usageMetadata&&q.usageMetadata.totalTokenCount&&q.usageMetadata.promptTokenCount&&q.usageMetadata.candidatesTokenCount&&(w.usage={promptTokens:q.usageMetadata.promptTokenCount,completionTokens:q.usageMetadata.candidatesTokenCount,totalTokens:q.usageMetadata.totalTokenCount}),q.candidates.length>0){let X=q.candidates[0];X.groundingMetadata&&w.partialMessages.push(Dt(E,((m=X.groundingMetadata.webSearchQueries)==null?void 0:m[0])||"",((r=X.groundingMetadata.groundingChunks)==null?void 0:r.map(G=>{var oe,Se;return {source:G.web?"web":"",url:((oe=G.web)==null?void 0:oe.uri)||"",title:((Se=G.web)==null?void 0:Se.title)||""}}))||[],((d=X.groundingMetadata.groundingSupports)==null?void 0:d.map(G=>{var oe,Se,nn;return {text:((oe=G.segment)==null?void 0:oe.text)||"",responseIndices:G.groundingChunkIndices||[],startIndex:((Se=G.segment)==null?void 0:Se.startIndex)||void 0,endIndex:((nn=G.segment)==null?void 0:nn.endIndex)||void 0,confidenceScores:G.confidenceScores||void 0}}))||[]));let z=X.safetyRatings;z&&z.length>0&&z.forEach(G=>{G.blocked&&w.partialMessages.push(Nt(E,G.category,G.probability,G.blocked,`Blocked content for category: ${G.category} with probability: ${G.probability}`));});}yield {partialResponse:w,buffer:t};}else throw new H({info:"Invalid response from model",cause:_.error})}catch(f){throw new H({info:`Malformed JSON received in stream: ${g}`,cause:f})}}}yield {partialResponse:{partialMessages:[]},buffer:h};})}getProxyCompleteChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getProxyStreamChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{if(!n||Object.keys(n).length===0){i(this.streamChatUrl);return}let s=new URL(this.streamChatUrl);Object.entries(n).forEach(([m,r])=>{r!=null&&s.searchParams.set(m,r);}),i(s.toString());})})}getProxyCompleteChatHeaders(e,t,n){return j(this,null,function*(){if(!t)return {};let i=S({},t);return delete i.host,delete i["content-length"],i})}getProxyStreamChatHeaders(e,t,n){return j(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,t,n)})}getModelPricing(){if(!(this.modelName in R))throw new H({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return R[this.modelName]}},Yt="gemini-1.5-flash-001",Kr="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",De=I(L,D).parse({name:Yt,description:Kr,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Yt]}),Yr=$,Wr=class extends F{constructor(e){super(De,e);}},Wt="gemini-1.5-flash-002",Jr="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",$e=I(L,D).parse({name:Wt,description:Jr,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Wt]}),Xr=$,Zr=class extends F{constructor(e){super($e,e);}},Jt="gemini-1.5-flash-latest",Qr="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Be=I(L,D).parse({name:Jt,description:Qr,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Jt]}),el=$,tl=class extends F{constructor(e){super(Be,e);}},Xt="gemini-1.5-flash",ol="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",Ae=I(L,D).parse({name:Xt,description:ol,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Xt]}),nl=$,il=class extends F{constructor(e){super(Ae,e);}},Zt="gemini-1.5-pro-001",al="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",qe=I(L,D).parse({name:Zt,description:al,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Zt]}),sl=$,rl=class extends F{constructor(e){super(qe,e);}},Qt="gemini-1.5-pro-002",ll="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",He=I(L,D).parse({name:Qt,description:ll,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Qt]}),ml=$,dl=class extends F{constructor(e){super(He,e);}},eo="gemini-1.5-pro-latest",cl="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",ze=I(L,D).parse({name:eo,description:cl,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[eo]}),pl=$,ul=class extends F{constructor(e){super(ze,e);}},to="gemini-1.5-pro",gl="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Ve=I(L,D).parse({name:to,description:gl,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[to]}),hl=$,fl=class extends F{constructor(e){super(Ve,e);}},yi="gemini-2.0-flash-exp",yl="Google's experimental multimodal model with enhanced capabilities. Designed for cutting-edge performance across complex and high-frequency tasks.",Di=I(L,D).parse({name:yi,description:yl,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[yi]});var oo="gemini-2.0-flash",bl="Google's Gemini 2.0 Flash model optimized for low-latency, high-performance tasks. Supports multimodal inputs including text, images, video, and audio with enhanced speed and efficiency.",Ke=I(L,D).parse({name:oo,description:bl,maxInputTokens:1048576,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[oo]}),Tl=$,Pl=class extends F{constructor(e){super(Ke,e);}},no="gemini-2.5-flash-lite",Ml="Google's most cost-efficient and fastest model in the 2.5 series. Optimized for high-volume, latency-sensitive tasks like translation and classification with enhanced reasoning capabilities.",Ye=I(L,D).parse({name:no,description:Ml,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.responseSchema(2,1,65536,4,.95).def,schema:k.responseSchema(2,1,65536,4,.95).schema},price:R[no]}),vl=$,kl=class extends F{constructor(e){super(Ye,e);}},io="gemini-2.5-flash-preview-04-17",_l="Google's best model in Gemini 2.5 family in terms of price-performance, offering well-rounded capabilities.",We=I(L,D).parse({name:io,description:_l,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.responseSchema(2,1,65536,4,.95).def,schema:k.responseSchema(2,1,65536,4,.95).schema},price:R[io]}),xl=$,Sl=class extends F{constructor(e){super(We,e);}},ao="gemini-2.5-flash",El="Google's Gemini 2.5 Flash model for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Je=I(L,D).parse({name:ao,description:El,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.responseSchema(2,1,65536,4,.95).def,schema:k.responseSchema(2,1,65536,4,.95).schema},price:R[ao]}),Cl=$,wl=class extends F{constructor(e){super(Je,e);}},so="gemini-2.5-pro-preview-03-25",Gl="Google's preview model in Gemini 2.5 family for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Xe=I(L,D).parse({name:so,description:Gl,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[so]}),Ol=$,Rl=class extends F{constructor(e){super(Xe,e);}},ro="gemini-2.5-pro",Il="Google's Gemini 2.5 Pro model for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Ze=I(L,D).parse({name:ro,description:Il,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[ro]}),jl=$,Fl=class extends F{constructor(e){super(Ze,e);}},lo="gemini-3-flash-preview",Ll="Google's Gemini 3 Flash Preview model - a lightweight and efficient AI model with enhanced multimodal understanding, reasoning, and advanced coding capabilities. Optimized for speed and cost-effectiveness. Supports Text, Image, Video, Audio, and PDF inputs. Knowledge cutoff: January 2025.",Qe=I(L,D).parse({name:lo,description:Ll,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[lo]}),Nl=$,Ul=class extends F{constructor(e){super(Qe,e);}},mo="gemini-3-pro-preview",Dl="Google's latest Gemini 3 Pro Preview model with enhanced multimodal understanding, reasoning, and thinking capabilities. Supports Text, Image, Video, Audio, and PDF inputs. Knowledge cutoff: January 2025.",et=I(L,D).parse({name:mo,description:Dl,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[mo]}),$l=$,Bl=class extends F{constructor(e){super(et,e);}},$i=[A],Bi=zod.z.enum([A]),Al=zod.z.object({embeddings:zod.z.array(zod.z.object({values:zod.z.array(zod.z.number())}))}),ql=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)})}),Hl=zod.z.object({model:zod.z.string().min(1).optional(),requests:zod.z.array(ql).min(1),outputDimensionality:zod.z.number().int().min(1).optional()}),po=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),getEmbeddingsUrl:zod.z.string().url().optional()}),Ai=class{constructor(e,t){this.version="v1";let n=po.parse(t);this.modelSchema=e,this.modelName=n.modelName,this.apiKey=n.apiKey,this.baseUrl=xe(n.baseUrl||co.baseUrl),this.getEmbeddingsUrl=xe(n.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(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.requests.reduce((t,n)=>t+n.length,0)}transformModelRequest(e){let t=Hl.safeParse(e);if(!t.success)throw new ie({info:"Invalid model request",cause:t.error});let n=t.data,i=n.model,s={outputDimensionality:n.outputDimensionality},m=Ce().parse(Oe(s)),r={modality:A,requests:n.requests.reduce((d,l)=>(d.push(...l.content.parts.map(p=>p.text)),d),[])};return {modelName:i,config:m,embeddingRequests:r}}transformConfig(e,t){let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:n.error});let i=n.data;return Object.keys(i).forEach(s=>{if(!this.modelSchema.config.def[s])throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${s}',
16
- available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(i).reduce((s,m)=>{let r=this.modelSchema.config.def[m].param,d=i[m];return s[r]=d,s},{})}transformEmbeddingRequests(e){let t=Fe().safeParse(e);if(!t.success)throw new de({info:"Invalid embedding requests",cause:t.error});if(e.modality!==A)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${A}' modality is supported for model : '${this.modelName}'`)});return {requests:t.data.requests.map(n=>({model:`models/${this.modelName}`,content:{parts:[{text:n}]}}))}}getGetEmbeddingsUrl(e,t){return j(this,null,function*(){return new Promise(n=>{n(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,t){return j(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,t){return j(this,null,function*(){return new Promise(n=>{let i=this.transformConfig(e),s=this.transformEmbeddingRequests(t);if(t.requests.length===0)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});i.outputDimensionality&&(s.requests.forEach(m=>{m.outputDimensionality=i.outputDimensionality;}),delete i.outputDimensionality),n(S(S(S({},this.getDefaultParams()),i),s));})})}transformGetEmbeddingsResponse(e){let t=Al.safeParse(e);if(t.success){let n=t.data.embeddings.map((i,s)=>({index:s,embedding:i.values}));return {encodingFormat:we,embeddings:n}}throw new H({info:"Invalid response from model",cause:t.error})}},qi="text-embedding-001",zl="text-embedding-001",Hi=J(Bi).parse({name:qi,description:zl,modalities:$i,maxInputTokens:2048,maxOutputTokens:768,config:{def:Ue.base(768).def,schema:Ue.base(768).schema}}),Vl=po,Kl=class extends Ai{constructor(e){super(Hi,e);}},zi="text-embedding-004",Yl="text-embedding-004",Vi=J(Bi).parse({name:zi,description:Yl,modalities:$i,maxInputTokens:2048,maxOutputTokens:768,config:{def:Ue.base(768).def,schema:Ue.base(768).schema}}),Wl=po,Jl=class extends Ai{constructor(e){super(Vi,e);}};var Xl="vertex",fe=class{constructor(){this.version="v1";this.name=Xl;this.chatModelFactories={[uo]:{model:tt,modelOptions:Ki,modelSchema:go},[ho]:{model:ot,modelOptions:Yi,modelSchema:fo},[xo]:{model:rt,modelOptions:Qi,modelSchema:So},[yo]:{model:nt,modelOptions:Wi,modelSchema:bo},[To]:{model:it,modelOptions:Ji,modelSchema:Po},[Mo]:{model:at,modelOptions:Xi,modelSchema:vo},[Eo]:{model:lt,modelOptions:ea,modelSchema:Co},[ko]:{model:st,modelOptions:Zi,modelSchema:_o},[wo]:{model:mt,modelOptions:ta,modelSchema:Go},[Oo]:{model:dt,modelOptions:oa,modelSchema:Ro},[Io]:{model:ct,modelOptions:na,modelSchema:jo},[Fo]:{model:pt,modelOptions:ia,modelSchema:Lo},[Do]:{model:gt,modelOptions:sa,modelSchema:$o},[No]:{model:ut,modelOptions:aa,modelSchema:Uo},[Bo]:{model:ht,modelOptions:ra,modelSchema:Ao},[qo]:{model:ft,modelOptions:la,modelSchema:Ho},[zo]:{model:yt,modelOptions:ma,modelSchema:Vo}};this.embeddingModelFactories={[Ko]:{model:bt,modelOptions:da,modelSchema:Yo},[Wo]:{model:Tt,modelOptions:ca,modelSchema:Jo},[Qo]:{model:Mt,modelOptions:ua,modelSchema:en},[Xo]:{model:Pt,modelOptions:pa,modelSchema:Zo}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,n)=>(t[n]=this.chatModelFactories[n].modelSchema,t),{})}chatModel(t){let n=t.modelName;if(!(n in this.chatModelFactories))throw new ve({info:`Vertex chat model: ${n} not found`,cause:new Error(`Vertex chat model: ${n} not found, available chat models:
13
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),n.forEach(r=>{r.content=r.content.filter(d=>d.modality!=="error"&&d.modality!=="search-result");});let i={parts:[]},s=[];if(n.forEach(r=>{switch(r.role){case Ee:r.content.forEach(d=>{if(d.modality===B)i.parts.push({text:d.value});else throw new C({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 E:{let d=[];r.content.forEach(l=>{if(l.modality===B)d.push({text:l.value});else if(l.modality===Y)d.push(S({function_call:{name:l.name,args:JSON.parse(l.arguments)}},l.thoughtSignature?{thought_signature:l.thoughtSignature}:{}));else if(l.modality===ge)l.value.type==="thinking"&&l.value.thinking&&d.push({text:l.value.thinking,thought:!0,thought_signature:l.value.signature});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[r.role],parts:d});}break;case Q:{let d=[];r.content.forEach(l=>{if(l.modality===B)d.push({text:l.value});else if(l.modality===le){if(l.value.type==="base64"){let p=l.value.base64;p=t(p),d.push({inline_data:{mime_type:`image/${l.value.mediaType}`,data:p}});}else if(l.value.type==="url")throw new C({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${l.value.type}'`)})}else if(l.modality===ue)if(l.value.type==="base64"){let p=l.value.base64;p=t(p),d.push({inline_data:{mime_type:"application/pdf",data:p}});}else l.value.type==="url"&&d.push({file_data:{mime_type:"application/pdf",file_uri:l.value.url}});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[r.role],parts:d});}break;case re:{let d=[];r.content.forEach(l=>{if(l.modality===me)d.push({function_response:{name:l.name,response:JSON.parse(l.data)}});else throw new C({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[r.role],parts:d});}break;default:throw new C({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' is not supported,
14
+ available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),s[0].role!==this.modelSchema.roles[Q])throw new C({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});let m=r=>r===this.modelSchema.roles[Q]||r===this.modelSchema.roles[re]?[this.modelSchema.roles[E]]:[this.modelSchema.roles[Q],this.modelSchema.roles[re]];for(let r=1;r<s.length;r++)if(!m(s[r-1].role).includes(s[r].role))throw new C({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${s[r].role}' after message with role : '${s[r-1].role}'`)});if(s[s.length-1].role!==this.modelSchema.roles[Q]&&s[s.length-1].role!==this.modelSchema.roles[re])throw new C({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires last message to be from user`)});return S({contents:s},i.parts.length>0?{system_instruction:i}:{})}stripAdditionalProperties(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.stripAdditionalProperties(n));let t={};for(let[n,i]of Object.entries(e))n!=="additionalProperties"&&(t[n]=this.stripAdditionalProperties(i));return t}transformTools(e,t){if(!this.modelSchema.modalities.includes(Y))throw new $t({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${Y}'`)});if((!e||e.length===0)&&!(t!=null&&t.googleSearchTool))return {tools:[]};let n=(e!=null?e:[]).map(i=>{let s=Cn().safeParse(i);if(!s.success)throw new $t({info:"Invalid tools",cause:s.error});return s.data}).map(i=>({name:i.definition.schema.name,description:i.definition.schema.description,parameters:this.stripAdditionalProperties(i.definition.schema.parameters)}));return {tools:[S(S({},n.length>0?{function_declarations:n}:{}),t!=null&&t.googleSearchTool?{google_search:{}}:{})]}}getCompleteChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getCompleteChatData(e,t,n){return j(this,null,function*(){let i=this.transformConfig(e,t,n),s=yield this.transformPdfMessages(t),m=this.transformMessages(s);if(m.messages&&m.messages.length===0)throw new C({info:"Messages are required",cause:new Error("Messages are required")});let r=this.transformTools(n||[],e);return S(S(S(S({},this.getDefaultParams()),i),m),r)})}transformCompleteChatResponse(e){var t,n,i,s,m,r;let d=Fr.safeParse(e);if(d.success){if(d.data.candidates.length===0)throw new H({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(d.data)}`)});let l={messages:[],usage:void 0,logProbs:void 0},p=d.data;p.usageMetadata&&(l.usage={promptTokens:p.usageMetadata.promptTokenCount,totalTokens:p.usageMetadata.totalTokenCount,completionTokens:p.usageMetadata.candidatesTokenCount||0});let h=p.candidates[0];if(h.content){let u=h.content.parts.map((g,f)=>{if("text"in g&&g.text!==void 0)return g.thought===!0?Gn(g.text,""):wn(g.text);if("functionCall"in g&&g.functionCall!==void 0)return On(f,`${g.functionCall.name}_${f}`,g.functionCall.name,JSON.stringify(g.functionCall.args),void 0,g.thoughtSignature)});l.messages.push({role:E,content:u});}h.groundingMetadata&&(l.messages.length===0?l.messages.push({role:E,content:[Ut(((t=h.groundingMetadata.webSearchQueries)==null?void 0:t[0])||"",((n=h.groundingMetadata.groundingChunks)==null?void 0:n.map(u=>{var g,f;return {source:u.web?"web":"",url:((g=u.web)==null?void 0:g.uri)||"",title:((f=u.web)==null?void 0:f.title)||""}}))||[],((i=h.groundingMetadata.groundingSupports)==null?void 0:i.map(u=>{var g,f,_;return {text:((g=u.segment)==null?void 0:g.text)||"",responseIndices:u.groundingChunkIndices||[],startIndex:((f=u.segment)==null?void 0:f.startIndex)||void 0,endIndex:((_=u.segment)==null?void 0:_.endIndex)||void 0,confidenceScores:u.confidenceScores||void 0}}))||[])]}):l.messages[0].content.push(Ut(((s=h.groundingMetadata.webSearchQueries)==null?void 0:s[0])||"",((m=h.groundingMetadata.groundingChunks)==null?void 0:m.map(u=>{var g,f;return {source:u.web?"web":"",url:((g=u.web)==null?void 0:g.uri)||"",title:((f=u.web)==null?void 0:f.title)||""}}))||[],((r=h.groundingMetadata.groundingSupports)==null?void 0:r.map(u=>{var g,f,_;return {text:((g=u.segment)==null?void 0:g.text)||"",responseIndices:u.groundingChunkIndices||[],startIndex:((f=u.segment)==null?void 0:f.startIndex)||void 0,endIndex:((_=u.segment)==null?void 0:_.endIndex)||void 0,confidenceScores:u.confidenceScores||void 0}}))||[])));let y=h.safetyRatings;if(y&&y.length>0&&y.forEach(u=>{u.blocked&&(l.messages.length===0?l.messages.push({role:E,content:[Lt(u.category,u.probability,u.blocked,`Blocked content for category: ${u.category} with probability: ${u.probability}`)]}):l.messages[0].content.push(Lt(u.category,u.probability,u.blocked,`Blocked content for category: ${u.category} with probability: ${u.probability}`)));}),l.messages.length>0)return l;if(l.messages.length===0&&h.finishReason==="SAFETY")throw new H({info:"Blocked content, model response finished with safety reason",cause:new Error("Blocked content, model response finished with safety reason")})}throw new H({info:"Invalid response from model",cause:d.error})}getStreamChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.streamChatUrl);})})}getStreamChatHeaders(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getStreamChatData(e,t,n){return j(this,null,function*(){let i=this.transformConfig(e,t,n),s=yield this.transformPdfMessages(t),m=this.transformMessages(s);if(m.messages&&m.messages.length===0)throw new C({info:"Messages are required",cause:new Error("Messages are required")});let r=this.transformTools(n||[],e);return S(S(S(S({},this.getDefaultParams()),i),m),r)})}transformStreamChatResponseChunk(e,t){return di(this,null,function*(){var n,i,s;let m=(t+e).split(",\r").filter(r=>r.trim()!=="");for(let r of m){let d=r;if(d=d.replace(/\n/g,""),d.startsWith("[")||d.startsWith(",{"))d=d.slice(1);else if(d.endsWith("]")){if(d==="]")return;d=d.slice(0,-1);}let l;try{l=JSON.parse(d);}catch(h){if(h instanceof SyntaxError){t=d;continue}else throw h}t="";let p=ci.safeParse(l);if(p.success){let h={partialMessages:[]},y=p.data;if(y.candidates.length>0){let u=y.candidates[0].content;u&&"parts"in u&&u.parts.length>0&&u.parts.forEach((g,f)=>{if("text"in g&&g.text!==void 0&&(g.thought===!0?h.partialMessages.push(Ft(E,g.text,"")):h.partialMessages.push(It(E,g.text))),"functionCall"in g&&g.functionCall!==void 0){let _=g.functionCall;h.partialMessages.push(jt(E,f,`${_.name}_${f}`,_.name,JSON.stringify(_.args),void 0,g.thoughtSignature));}});}if(y.usageMetadata&&(h.usage={promptTokens:y.usageMetadata.promptTokenCount,completionTokens:y.usageMetadata.candidatesTokenCount,totalTokens:y.usageMetadata.totalTokenCount}),y.candidates.length>0){let u=y.candidates[0];u.groundingMetadata&&h.partialMessages.push(Dt(E,((n=u.groundingMetadata.webSearchQueries)==null?void 0:n[0])||"",((i=u.groundingMetadata.groundingChunks)==null?void 0:i.map(f=>{var _,w;return {source:f.web?"web":"",url:((_=f.web)==null?void 0:_.uri)||"",title:((w=f.web)==null?void 0:w.title)||""}}))||[],((s=u.groundingMetadata.groundingSupports)==null?void 0:s.map(f=>{var _,w,q;return {text:((_=f.segment)==null?void 0:_.text)||"",responseIndices:f.groundingChunkIndices||[],startIndex:((w=f.segment)==null?void 0:w.startIndex)||void 0,endIndex:((q=f.segment)==null?void 0:q.endIndex)||void 0,confidenceScores:f.confidenceScores||void 0}}))||[]));let g=u.safetyRatings;g&&g.length>0&&g.forEach(f=>{f.blocked&&h.partialMessages.push(Nt(E,f.category,f.probability,f.blocked,`Blocked content for category: ${f.category} with probability: ${f.probability}`));});}yield {partialResponse:h,buffer:t};}else throw new H({info:"Invalid response from model",cause:p.error})}yield {partialResponse:{partialMessages:[]},buffer:t};})}transformProxyStreamChatResponseChunk(e,t,n,i,s){return di(this,null,function*(){var m,r,d;if((s==null?void 0:s.alt)!=="sse"){yield*rn(fr(this.transformStreamChatResponseChunk(e,t)));return}let l=t+e,p=[],h="",y=0;for(;y<l.length;){let u=l.indexOf(`
15
+ `,y);if(u===-1){h=l.substring(y);break}else {let g=l.substring(y,u).trim();g&&p.push(g),y=u+1;}}for(let u of p){if(u==="data: [DONE]")return;if(u.startsWith("data: ")){let g=u.substring(6);try{let f=JSON.parse(g),_=ci.safeParse(f);if(_.success){let w={partialMessages:[]},q=_.data;if(q.candidates.length>0){let X=q.candidates[0].content;X&&"parts"in X&&X.parts.length>0&&X.parts.forEach((z,O)=>{if("text"in z&&z.text!==void 0&&(z.thought===!0?w.partialMessages.push(Ft(E,z.text,"")):w.partialMessages.push(It(E,z.text))),"functionCall"in z&&z.functionCall!==void 0){let oe=z.functionCall;w.partialMessages.push(jt(E,O,`${oe.name}_${O}`,oe.name,JSON.stringify(oe.args),void 0,z.thoughtSignature));}});}if(q.usageMetadata&&q.usageMetadata.totalTokenCount&&q.usageMetadata.promptTokenCount&&q.usageMetadata.candidatesTokenCount&&(w.usage={promptTokens:q.usageMetadata.promptTokenCount,completionTokens:q.usageMetadata.candidatesTokenCount,totalTokens:q.usageMetadata.totalTokenCount}),q.candidates.length>0){let X=q.candidates[0];X.groundingMetadata&&w.partialMessages.push(Dt(E,((m=X.groundingMetadata.webSearchQueries)==null?void 0:m[0])||"",((r=X.groundingMetadata.groundingChunks)==null?void 0:r.map(O=>{var oe,Se;return {source:O.web?"web":"",url:((oe=O.web)==null?void 0:oe.uri)||"",title:((Se=O.web)==null?void 0:Se.title)||""}}))||[],((d=X.groundingMetadata.groundingSupports)==null?void 0:d.map(O=>{var oe,Se,nn;return {text:((oe=O.segment)==null?void 0:oe.text)||"",responseIndices:O.groundingChunkIndices||[],startIndex:((Se=O.segment)==null?void 0:Se.startIndex)||void 0,endIndex:((nn=O.segment)==null?void 0:nn.endIndex)||void 0,confidenceScores:O.confidenceScores||void 0}}))||[]));let z=X.safetyRatings;z&&z.length>0&&z.forEach(O=>{O.blocked&&w.partialMessages.push(Nt(E,O.category,O.probability,O.blocked,`Blocked content for category: ${O.category} with probability: ${O.probability}`));});}yield {partialResponse:w,buffer:t};}else throw new H({info:"Invalid response from model",cause:_.error})}catch(f){throw new H({info:`Malformed JSON received in stream: ${g}`,cause:f})}}}yield {partialResponse:{partialMessages:[]},buffer:h};})}getProxyCompleteChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{i(this.completeChatUrl);})})}getProxyStreamChatUrl(e,t,n){return j(this,null,function*(){return new Promise(i=>{if(!n||Object.keys(n).length===0){i(this.streamChatUrl);return}let s=new URL(this.streamChatUrl);Object.entries(n).forEach(([m,r])=>{r!=null&&s.searchParams.set(m,r);}),i(s.toString());})})}getProxyCompleteChatHeaders(e,t,n){return j(this,null,function*(){if(!t)return {};let i=S({},t);return delete i.host,delete i["content-length"],i})}getProxyStreamChatHeaders(e,t,n){return j(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,t,n)})}getModelPricing(){if(!(this.modelName in R))throw new H({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return R[this.modelName]}},Yt="gemini-1.5-flash-001",Kr="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",De=I(L,D).parse({name:Yt,description:Kr,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Yt]}),Yr=$,Wr=class extends F{constructor(e){super(De,e);}},Wt="gemini-1.5-flash-002",Jr="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",$e=I(L,D).parse({name:Wt,description:Jr,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Wt]}),Xr=$,Zr=class extends F{constructor(e){super($e,e);}},Jt="gemini-1.5-flash-latest",Qr="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Be=I(L,D).parse({name:Jt,description:Qr,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Jt]}),el=$,tl=class extends F{constructor(e){super(Be,e);}},Xt="gemini-1.5-flash",ol="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",Ae=I(L,D).parse({name:Xt,description:ol,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Xt]}),nl=$,il=class extends F{constructor(e){super(Ae,e);}},Zt="gemini-1.5-pro-001",al="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",qe=I(L,D).parse({name:Zt,description:al,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Zt]}),sl=$,rl=class extends F{constructor(e){super(qe,e);}},Qt="gemini-1.5-pro-002",ll="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",ze=I(L,D).parse({name:Qt,description:ll,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[Qt]}),ml=$,dl=class extends F{constructor(e){super(ze,e);}},eo="gemini-1.5-pro-latest",cl="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",He=I(L,D).parse({name:eo,description:cl,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[eo]}),pl=$,ul=class extends F{constructor(e){super(He,e);}},to="gemini-1.5-pro",gl="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Ve=I(L,D).parse({name:to,description:gl,maxInputTokens:2e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[to]}),hl=$,fl=class extends F{constructor(e){super(Ve,e);}},yi="gemini-2.0-flash-exp",yl="Google's experimental multimodal model with enhanced capabilities. Designed for cutting-edge performance across complex and high-frequency tasks.",Di=I(L,D).parse({name:yi,description:yl,maxInputTokens:1e6,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[yi]});var oo="gemini-2.0-flash",bl="Google's Gemini 2.0 Flash model optimized for low-latency, high-performance tasks. Supports multimodal inputs including text, images, video, and audio with enhanced speed and efficiency.",Ke=I(L,D).parse({name:oo,description:bl,maxInputTokens:1048576,maxOutputTokens:8192,roles:N,modalities:U,config:{def:k.responseSchema(2,1,8192,4,.95).def,schema:k.responseSchema(2,1,8192,4,.95).schema},price:R[oo]}),Tl=$,Pl=class extends F{constructor(e){super(Ke,e);}},no="gemini-2.5-flash-lite",Ml="Google's most cost-efficient and fastest model in the 2.5 series. Optimized for high-volume, latency-sensitive tasks like translation and classification with enhanced reasoning capabilities.",Ye=I(L,D).parse({name:no,description:Ml,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.responseSchema(2,1,65536,4,.95).def,schema:k.responseSchema(2,1,65536,4,.95).schema},price:R[no]}),vl=$,kl=class extends F{constructor(e){super(Ye,e);}},io="gemini-2.5-flash-preview-04-17",_l="Google's best model in Gemini 2.5 family in terms of price-performance, offering well-rounded capabilities.",We=I(L,D).parse({name:io,description:_l,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,24576).def,schema:k.reasoning(2,1,65536,4,.95,1,24576).schema},price:R[io]}),xl=$,Sl=class extends F{constructor(e){super(We,e);}},ao="gemini-2.5-flash",El="Google's Gemini 2.5 Flash model for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Je=I(L,D).parse({name:ao,description:El,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,24576).def,schema:k.reasoning(2,1,65536,4,.95,1,24576).schema},price:R[ao]}),Cl=$,wl=class extends F{constructor(e){super(Je,e);}},so="gemini-2.5-pro-preview-03-25",Ol="Google's preview model in Gemini 2.5 family for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Xe=I(L,D).parse({name:so,description:Ol,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[so]}),Gl=$,Rl=class extends F{constructor(e){super(Xe,e);}},ro="gemini-2.5-pro",Il="Google's Gemini 2.5 Pro model for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Ze=I(L,D).parse({name:ro,description:Il,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[ro]}),jl=$,Fl=class extends F{constructor(e){super(Ze,e);}},lo="gemini-3-flash-preview",Ll="Google's Gemini 3 Flash Preview model - a lightweight and efficient AI model with enhanced multimodal understanding, reasoning, and advanced coding capabilities. Optimized for speed and cost-effectiveness. Supports Text, Image, Video, Audio, and PDF inputs. Knowledge cutoff: January 2025.",Qe=I(L,D).parse({name:lo,description:Ll,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[lo]}),Nl=$,Ul=class extends F{constructor(e){super(Qe,e);}},mo="gemini-3-pro-preview",Dl="Google's latest Gemini 3 Pro Preview model with enhanced multimodal understanding, reasoning, and thinking capabilities. Supports Text, Image, Video, Audio, and PDF inputs. Knowledge cutoff: January 2025.",et=I(L,D).parse({name:mo,description:Dl,maxInputTokens:1048576,maxOutputTokens:65536,roles:N,modalities:U,config:{def:k.reasoning(2,1,65536,4,.95,1,65536).def,schema:k.reasoning(2,1,65536,4,.95,1,65536).schema},price:R[mo]}),$l=$,Bl=class extends F{constructor(e){super(et,e);}},$i=[A],Bi=zod.z.enum([A]),Al=zod.z.object({embeddings:zod.z.array(zod.z.object({values:zod.z.array(zod.z.number())}))}),ql=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)})}),zl=zod.z.object({model:zod.z.string().min(1).optional(),requests:zod.z.array(ql).min(1),outputDimensionality:zod.z.number().int().min(1).optional()}),po=zod.z.object({modelName:zod.z.string(),apiKey:zod.z.string(),baseUrl:zod.z.string().url().optional(),getEmbeddingsUrl:zod.z.string().url().optional()}),Ai=class{constructor(e,t){this.version="v1";let n=po.parse(t);this.modelSchema=e,this.modelName=n.modelName,this.apiKey=n.apiKey,this.baseUrl=xe(n.baseUrl||co.baseUrl),this.getEmbeddingsUrl=xe(n.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(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.requests.reduce((t,n)=>t+n.length,0)}transformModelRequest(e){let t=zl.safeParse(e);if(!t.success)throw new ie({info:"Invalid model request",cause:t.error});let n=t.data,i=n.model,s={outputDimensionality:n.outputDimensionality},m=Ce().parse(Ge(s)),r={modality:A,requests:n.requests.reduce((d,l)=>(d.push(...l.content.parts.map(p=>p.text)),d),[])};return {modelName:i,config:m,embeddingRequests:r}}transformConfig(e,t){let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:n.error});let i=n.data;return Object.keys(i).forEach(s=>{if(!this.modelSchema.config.def[s])throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${s}',
16
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(i).reduce((s,m)=>{let r=this.modelSchema.config.def[m].param,d=i[m];return s[r]=d,s},{})}transformEmbeddingRequests(e){let t=Fe().safeParse(e);if(!t.success)throw new de({info:"Invalid embedding requests",cause:t.error});if(e.modality!==A)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${A}' modality is supported for model : '${this.modelName}'`)});return {requests:t.data.requests.map(n=>({model:`models/${this.modelName}`,content:{parts:[{text:n}]}}))}}getGetEmbeddingsUrl(e,t){return j(this,null,function*(){return new Promise(n=>{n(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,t){return j(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,t){return j(this,null,function*(){return new Promise(n=>{let i=this.transformConfig(e),s=this.transformEmbeddingRequests(t);if(t.requests.length===0)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});i.outputDimensionality&&(s.requests.forEach(m=>{m.outputDimensionality=i.outputDimensionality;}),delete i.outputDimensionality),n(S(S(S({},this.getDefaultParams()),i),s));})})}transformGetEmbeddingsResponse(e){let t=Al.safeParse(e);if(t.success){let n=t.data.embeddings.map((i,s)=>({index:s,embedding:i.values}));return {encodingFormat:we,embeddings:n}}throw new H({info:"Invalid response from model",cause:t.error})}},qi="text-embedding-001",Hl="text-embedding-001",zi=J(Bi).parse({name:qi,description:Hl,modalities:$i,maxInputTokens:2048,maxOutputTokens:768,config:{def:Ue.base(768).def,schema:Ue.base(768).schema}}),Vl=po,Kl=class extends Ai{constructor(e){super(zi,e);}},Hi="text-embedding-004",Yl="text-embedding-004",Vi=J(Bi).parse({name:Hi,description:Yl,modalities:$i,maxInputTokens:2048,maxOutputTokens:768,config:{def:Ue.base(768).def,schema:Ue.base(768).schema}}),Wl=po,Jl=class extends Ai{constructor(e){super(Vi,e);}};var Xl="vertex",fe=class{constructor(){this.version="v1";this.name=Xl;this.chatModelFactories={[uo]:{model:tt,modelOptions:Ki,modelSchema:go},[ho]:{model:ot,modelOptions:Yi,modelSchema:fo},[xo]:{model:rt,modelOptions:Qi,modelSchema:So},[yo]:{model:nt,modelOptions:Wi,modelSchema:bo},[To]:{model:it,modelOptions:Ji,modelSchema:Po},[Mo]:{model:at,modelOptions:Xi,modelSchema:vo},[Eo]:{model:lt,modelOptions:ea,modelSchema:Co},[ko]:{model:st,modelOptions:Zi,modelSchema:_o},[wo]:{model:mt,modelOptions:ta,modelSchema:Oo},[Go]:{model:dt,modelOptions:oa,modelSchema:Ro},[Io]:{model:ct,modelOptions:na,modelSchema:jo},[Fo]:{model:pt,modelOptions:ia,modelSchema:Lo},[Do]:{model:gt,modelOptions:sa,modelSchema:$o},[No]:{model:ut,modelOptions:aa,modelSchema:Uo},[Bo]:{model:ht,modelOptions:ra,modelSchema:Ao},[qo]:{model:ft,modelOptions:la,modelSchema:zo},[Ho]:{model:yt,modelOptions:ma,modelSchema:Vo}};this.embeddingModelFactories={[Ko]:{model:bt,modelOptions:da,modelSchema:Yo},[Wo]:{model:Tt,modelOptions:ca,modelSchema:Jo},[Qo]:{model:Mt,modelOptions:ua,modelSchema:en},[Xo]:{model:Pt,modelOptions:pa,modelSchema:Zo}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((t,n)=>(t[n]=this.chatModelFactories[n].modelSchema,t),{})}chatModel(t){let n=t.modelName;if(!(n in this.chatModelFactories))throw new ve({info:`Vertex chat model: ${n} not found`,cause:new Error(`Vertex chat model: ${n} not found, available chat models:
17
17
  ${this.chatModelLiterals().join(", ")}`)});let i=this.chatModelFactories[n].model,s=this.chatModelFactories[n].modelOptions.parse(t);return new i(s)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((t,n)=>(t[n]=this.embeddingModelFactories[n].modelSchema,t),{})}embeddingModel(t){let n=t.modelName;if(!(n in this.embeddingModelFactories))throw new ve({info:`Vertex embedding model: ${n} not found`,cause:new Error(`Vertex embedding model: ${n} not found, available embedding models:
18
- ${this.embeddingModelLiterals().join(", ")}`)});let i=this.embeddingModelFactories[n].model,s=this.embeddingModelFactories[n].modelOptions.parse(t);return new i(s)}};fe.baseUrl=(t,n,i="google")=>`https://${t}-aiplatform.googleapis.com/v1/projects/${n}/locations/${t}/publishers/${i}`;var T={"gemini-1.0-pro-001":{modelName:"gemini-1.0-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro-vision":{modelName:"gemini-1.0-pro-vision",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro":{modelName:"gemini-1.0-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.5-flash-001":{modelName:"gemini-1.5-flash-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-flash-002":{modelName:"gemini-1.5-flash-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.0375,outputPricePerMillion:.15}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}}]},"gemini-1.5-flash":{modelName:"gemini-1.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-pro-001":{modelName:"gemini-1.5-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro-002":{modelName:"gemini-1.5-pro-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro":{modelName:"gemini-1.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-2.0-flash-exp":{modelName:"gemini-2.0-flash-exp",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-2.0-flash":{modelName:"gemini-2.0-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-2.5-flash-lite":{modelName:"gemini-2.5-flash-lite",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-1.5-flash-latest":{modelName:"gemini-1.5-flash-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.01875,outputPricePerMillion:.075}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.0375,outputPricePerMillion:.15}}}]},"gemini-1.5-pro-latest":{modelName:"gemini-1.5-pro-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.3125,outputPricePerMillion:1.25}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.625,outputPricePerMillion:2.5}}}]},"gemini-2.5-flash-preview-04-17":{modelName:"gemini-2.5-flash-preview-04-17",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:2}}}]},"gemini-2.5-pro-preview-03-25":{modelName:"gemini-2.5-pro-preview-03-25",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:15}}}]},"gemini-2.5-flash":{modelName:"gemini-2.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.3,outputPricePerMillion:2.5}}}]},"gemini-2.5-pro":{modelName:"gemini-2.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:15}}}]},"gemini-3-pro-preview":{modelName:"gemini-3-pro-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:2,outputPricePerMillion:12}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:4,outputPricePerMillion:18}}}]},"gemini-3-flash-preview":{modelName:"gemini-3-flash-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:3}}}]}};var v=zod.z.discriminatedUnion("authType",[zod.z.object({authType:zod.z.literal("accessToken"),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()}),zod.z.object({authType:zod.z.literal("serviceAccount"),serviceAccount:zod.z.object({client_email:zod.z.string().email(),private_key:zod.z.string(),type:zod.z.string().optional(),project_id:zod.z.string().optional(),private_key_id:zod.z.string().optional(),client_id:zod.z.string().optional(),auth_uri:zod.z.string().url().optional(),token_uri:zod.z.string().url().optional(),auth_provider_x509_cert_url:zod.z.string().url().optional(),client_x509_cert_url:zod.z.string().url().optional(),universe_domain:zod.z.string().optional()}),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(),tokenLifetimeHours:zod.z.number().min(.1).max(24).default(1)})]),M=class extends F{constructor(n,i){let s=v.parse(i),m;if(s.baseUrl)m=s.baseUrl;else if(s.location&&s.projectId)m=fe.baseUrl(s.location,s.projectId,s.publisher);else throw new ke({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(n,{modelName:s.modelName,apiKey:"random-api-key",completeChatUrl:`${m}/models/${s.modelName}:generateContent`,streamChatUrl:`${m}/models/${s.modelName}:streamGenerateContent`});this.version="v1";this.accessToken=null;this.tokenExpiry=null;this.modelSchema=n,this.modelName=s.modelName,this.authOptions=s,this.location=s.location,this.projectId=s.projectId,this.publisher=s.publisher,s.authType==="accessToken"&&(this.accessToken=s.accessToken);}getAccessToken(){return Z(this,null,function*(){if(this.accessToken&&this.tokenExpiry&&Date.now()<this.tokenExpiry)return this.accessToken;if(this.authOptions.authType==="serviceAccount")try{let n=this.authOptions.serviceAccount,i=Math.floor(Date.now()/1e3),s=yield new jose.SignJWT({scope:"https://www.googleapis.com/auth/cloud-platform",aud:"https://oauth2.googleapis.com/token"}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuedAt(i).setExpirationTime(i+this.authOptions.tokenLifetimeHours*3600).setIssuer(n.client_email).setSubject(n.client_email).sign(yield this.importPrivateKey(n.private_key)),m=yield fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s})});if(!m.ok){let d=yield m.text();throw new Error(`Token exchange failed: ${m.status} ${d}`)}let r=yield m.json();if(!r.access_token)throw new Error(`No access token received from Google OAuth: ${r.error||"Unknown error"}`);return this.tokenExpiry=Date.now()+this.authOptions.tokenLifetimeHours*3600*1e3-5*60*1e3,this.accessToken=r.access_token,this.accessToken}catch(n){throw new ke({info:`Failed to generate service account token: ${n instanceof Error?n.message:String(n)}`,cause:n instanceof Error?n:new Error(String(n))})}if(this.accessToken)return this.accessToken;throw new ke({info:"No valid access token available",cause:new Error("No valid access token available")})})}importPrivateKey(n){return Z(this,null,function*(){let i=n.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s/g,""),s=atob(i),m=new Uint8Array(s.length);for(let r=0;r<s.length;r++)m[r]=s.charCodeAt(r);return yield crypto.subtle.importKey("pkcs8",m,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])})}ensureToken(){return Z(this,null,function*(){this.authOptions.authType==="serviceAccount"&&(yield this.getAccessToken());})}getDefaultHeaders(){return P(b({},super.getDefaultHeaders()),{Authorization:`Bearer ${this.accessToken}`})}getCompleteChatHeaders(n,i,s){return Z(this,null,function*(){return yield this.ensureToken(),this.getDefaultHeaders()})}getStreamChatHeaders(n,i,s){return Z(this,null,function*(){return yield this.ensureToken(),this.getDefaultHeaders()})}getModelPricing(){if(!(this.modelName in T))throw new H({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return T[this.modelName]}};var uo="gemini-1.5-flash-001",go=P(b({},De),{price:T[uo]}),Ki=v,tt=class extends M{constructor(t){super(go,t);}};var ho="gemini-1.5-flash-002",fo=P(b({},$e),{price:T[ho]}),Yi=v,ot=class extends M{constructor(t){super(fo,t);}};var yo="gemini-1.5-flash",bo=P(b({},Ae),{price:T[yo]}),Wi=v,nt=class extends M{constructor(t){super(bo,t);}};var To="gemini-1.5-pro-001",Po=P(b({},qe),{price:T[To]}),Ji=v,it=class extends M{constructor(t){super(Po,t);}};var Mo="gemini-1.5-pro-002",vo=P(b({},He),{price:T[Mo]}),Xi=v,at=class extends M{constructor(t){super(vo,t);}};var ko="gemini-1.5-pro",_o=P(b({},Ve),{price:T[ko]}),Zi=v,st=class extends M{constructor(t){super(_o,t);}};var xo="gemini-1.5-flash-latest",So=P(b({},Be),{price:T[xo]}),Qi=v,rt=class extends M{constructor(t){super(So,t);}};var Eo="gemini-1.5-pro-latest",Co=P(b({},ze),{price:T[Eo]}),ea=v,lt=class extends M{constructor(t){super(Co,t);}};var wo="gemini-2.0-flash-exp",Go=P(b({},Di),{price:T[wo]}),ta=v,mt=class extends M{constructor(t){super(Go,t);}};var Oo="gemini-2.0-flash",Ro=P(b({},Ke),{price:T[Oo]}),oa=v,dt=class extends M{constructor(t){super(Ro,t);}};var Io="gemini-2.5-flash-lite",jo=P(b({},Ye),{price:T[Io]}),na=v,ct=class extends M{constructor(t){super(jo,t);}};var Fo="gemini-2.5-flash-preview-04-17",Lo=P(b({},We),{price:T[Fo]}),ia=v,pt=class extends M{constructor(t){super(Lo,t);}};var No="gemini-2.5-flash",Uo=P(b({},Je),{price:T[No]}),aa=v,ut=class extends M{constructor(t){super(Uo,t);}};var Do="gemini-2.5-pro-preview-03-25",$o=P(b({},Xe),{price:T[Do]}),sa=v,gt=class extends M{constructor(t){super($o,t);}};var Bo="gemini-2.5-pro",Ao=P(b({},Ze),{price:T[Bo]}),ra=v,ht=class extends M{constructor(t){super(Ao,t);}};var qo="gemini-3-flash-preview",Ho=P(b({},Qe),{price:T[qo]}),la=v,ft=class extends M{constructor(t){super(Ho,t);}};var zo="gemini-3-pro-preview",Vo=P(b({},et),{price:T[zo]}),ma=v,yt=class extends M{constructor(t){super(Vo,t);}};var ce=[A],pe=zod.z.enum([A]);var ga=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 ha=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 se=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()}),te=class{constructor(t,n){this.version="v1";let i=se.parse(n);this.modelSchema=t,this.modelName=i.modelName,this.accessToken=i.accessToken;let s;if(i.baseUrl)s=i.baseUrl;else if(i.location&&i.projectId)s=fe.baseUrl(i.location,i.projectId,i.publisher);else throw new ke({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(t){return {shouldRetry:!1,delayMs:0}}getTokenCount(t){return t.requests.reduce((n,i)=>n+i.length,0)}transformModelRequest(t){var l,p,h,y;let n=ha.safeParse(t);if(!n.success)throw new ie({info:"Invalid model request",cause:n.error});let i=n.data,s=i.model,m={autoTruncate:((l=i.parameters)==null?void 0:l.auto_truncate)||((p=i.parameters)==null?void 0:p.autoTruncate),dimensions:((h=i.parameters)==null?void 0:h.output_dimensionality)||((y=i.parameters)==null?void 0:y.outputDimensionality)},r=Ce().parse(Oe(m)),d={modality:A,requests:i.instances.map(u=>u.content)};return {modelName:s,config:r,embeddingRequests:d}}transformConfig(t,n){let i=this.modelSchema.config.schema.safeParse(t);if(!i.success)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let s=i.data;return Object.keys(s).forEach(r=>{if(!this.modelSchema.config.def[r])throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${r}',
19
- available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),{parameters:Object.keys(s).reduce((r,d)=>{let p=this.modelSchema.config.def[d].param,h=s[d];return r[p]=h,r},{})}}transformEmbeddingRequests(t){let n=Fe().safeParse(t);if(!n.success)throw new de({info:"Invalid embedding requests",cause:n.error});if(t.modality!==A)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${A}' modality is supported for model : '${this.modelName}'`)});return {instances:n.data.requests.map(s=>({content:s}))}}getGetEmbeddingsUrl(t,n){return Z(this,null,function*(){return new Promise(i=>{i(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(t,n){return Z(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getGetEmbeddingsData(t,n){return Z(this,null,function*(){return new Promise(i=>{if(n.requests.length===0)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});i(b(b(b({},this.getDefaultParams()),this.transformConfig(t)),this.transformEmbeddingRequests(n)));})})}transformGetEmbeddingsResponse(t){let n=ga.safeParse(t);if(n.success){let s=n.data.predictions.map((m,r)=>({index:r,embedding:m.embeddings.values}));return {encodingFormat:we,embeddings:s}}throw new H({info:"Invalid response from model",cause:n.error})}};var tn=e=>W({param:"output_dimensionality",title:_e.DIMENSIONS.title,description:_e.DIMENSIONS.description,min:1,max:e,step:1,default:e}),on=Ge({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 fa=e=>zod.z.object({dimensions:tn(e).schema,autoTruncate:on.schema}),ya=e=>({dimensions:tn(e).def,autoTruncate:on.def});var K={base:e=>({def:ya(e),schema:fa(e)})};var Ko="text-embedding-004",om="text-embedding-004",Yo=J(pe).parse({name:Ko,description:om,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),da=se,bt=class extends te{constructor(t){super(Yo,t);}};var Wo="text-multilingual-embedding-002",nm="text-multilingual-embedding-002",Jo=J(pe).parse({name:Wo,description:nm,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),ca=se,Tt=class extends te{constructor(t){super(Jo,t);}};var Xo="textembedding-gecko-multilingual@001",im="textembedding-gecko-multilingual@001",Zo=J(pe).parse({name:Xo,description:im,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),pa=se,Pt=class extends te{constructor(t){super(Zo,t);}};var Qo="textembedding-gecko@003",am="textembedding-gecko@003",en=J(pe).parse({name:Qo,description:am,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),ua=se,Mt=class extends te{constructor(t){super(en,t);}};
18
+ ${this.embeddingModelLiterals().join(", ")}`)});let i=this.embeddingModelFactories[n].model,s=this.embeddingModelFactories[n].modelOptions.parse(t);return new i(s)}};fe.baseUrl=(t,n,i="google")=>`https://${t}-aiplatform.googleapis.com/v1/projects/${n}/locations/${t}/publishers/${i}`;var T={"gemini-1.0-pro-001":{modelName:"gemini-1.0-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro-vision":{modelName:"gemini-1.0-pro-vision",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.0-pro":{modelName:"gemini-1.0-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:1.5}}}]},"gemini-1.5-flash-001":{modelName:"gemini-1.5-flash-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-flash-002":{modelName:"gemini-1.5-flash-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.0375,outputPricePerMillion:.15}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}}]},"gemini-1.5-flash":{modelName:"gemini-1.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.075,outputPricePerMillion:.3}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-1.5-pro-001":{modelName:"gemini-1.5-pro-001",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro-002":{modelName:"gemini-1.5-pro-002",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-1.5-pro":{modelName:"gemini-1.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:5}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:10}}}]},"gemini-2.0-flash-exp":{modelName:"gemini-2.0-flash-exp",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-2.0-flash":{modelName:"gemini-2.0-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.15,outputPricePerMillion:.6}}}]},"gemini-2.5-flash-lite":{modelName:"gemini-2.5-flash-lite",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.1,outputPricePerMillion:.4}}}]},"gemini-1.5-flash-latest":{modelName:"gemini-1.5-flash-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.01875,outputPricePerMillion:.075}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.0375,outputPricePerMillion:.15}}}]},"gemini-1.5-pro-latest":{modelName:"gemini-1.5-pro-latest",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:128e3,prices:{base:{inputPricePerMillion:.3125,outputPricePerMillion:1.25}}},{minTokens:128001,maxTokens:null,prices:{base:{inputPricePerMillion:.625,outputPricePerMillion:2.5}}}]},"gemini-2.5-flash-preview-04-17":{modelName:"gemini-2.5-flash-preview-04-17",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:2}}}]},"gemini-2.5-pro-preview-03-25":{modelName:"gemini-2.5-pro-preview-03-25",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:15}}}]},"gemini-2.5-flash":{modelName:"gemini-2.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.3,outputPricePerMillion:2.5}}}]},"gemini-2.5-pro":{modelName:"gemini-2.5-pro",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:1.25,outputPricePerMillion:10}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:2.5,outputPricePerMillion:15}}}]},"gemini-3-pro-preview":{modelName:"gemini-3-pro-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:2e5,prices:{base:{inputPricePerMillion:2,outputPricePerMillion:12}}},{minTokens:200001,maxTokens:null,prices:{base:{inputPricePerMillion:4,outputPricePerMillion:18}}}]},"gemini-3-flash-preview":{modelName:"gemini-3-flash-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:3}}}]}};var v=zod.z.discriminatedUnion("authType",[zod.z.object({authType:zod.z.literal("accessToken"),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()}),zod.z.object({authType:zod.z.literal("serviceAccount"),serviceAccount:zod.z.object({client_email:zod.z.string().email(),private_key:zod.z.string(),type:zod.z.string().optional(),project_id:zod.z.string().optional(),private_key_id:zod.z.string().optional(),client_id:zod.z.string().optional(),auth_uri:zod.z.string().url().optional(),token_uri:zod.z.string().url().optional(),auth_provider_x509_cert_url:zod.z.string().url().optional(),client_x509_cert_url:zod.z.string().url().optional(),universe_domain:zod.z.string().optional()}),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(),tokenLifetimeHours:zod.z.number().min(.1).max(24).default(1)})]),M=class extends F{constructor(n,i){let s=v.parse(i),m;if(s.baseUrl)m=s.baseUrl;else if(s.location&&s.projectId)m=fe.baseUrl(s.location,s.projectId,s.publisher);else throw new ke({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(n,{modelName:s.modelName,apiKey:"random-api-key",completeChatUrl:`${m}/models/${s.modelName}:generateContent`,streamChatUrl:`${m}/models/${s.modelName}:streamGenerateContent`});this.version="v1";this.accessToken=null;this.tokenExpiry=null;this.modelSchema=n,this.modelName=s.modelName,this.authOptions=s,this.location=s.location,this.projectId=s.projectId,this.publisher=s.publisher,s.authType==="accessToken"&&(this.accessToken=s.accessToken);}getAccessToken(){return Z(this,null,function*(){if(this.accessToken&&this.tokenExpiry&&Date.now()<this.tokenExpiry)return this.accessToken;if(this.authOptions.authType==="serviceAccount")try{let n=this.authOptions.serviceAccount,i=Math.floor(Date.now()/1e3),s=yield new jose.SignJWT({scope:"https://www.googleapis.com/auth/cloud-platform",aud:"https://oauth2.googleapis.com/token"}).setProtectedHeader({alg:"RS256",typ:"JWT"}).setIssuedAt(i).setExpirationTime(i+this.authOptions.tokenLifetimeHours*3600).setIssuer(n.client_email).setSubject(n.client_email).sign(yield this.importPrivateKey(n.private_key)),m=yield fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:s})});if(!m.ok){let d=yield m.text();throw new Error(`Token exchange failed: ${m.status} ${d}`)}let r=yield m.json();if(!r.access_token)throw new Error(`No access token received from Google OAuth: ${r.error||"Unknown error"}`);return this.tokenExpiry=Date.now()+this.authOptions.tokenLifetimeHours*3600*1e3-5*60*1e3,this.accessToken=r.access_token,this.accessToken}catch(n){throw new ke({info:`Failed to generate service account token: ${n instanceof Error?n.message:String(n)}`,cause:n instanceof Error?n:new Error(String(n))})}if(this.accessToken)return this.accessToken;throw new ke({info:"No valid access token available",cause:new Error("No valid access token available")})})}importPrivateKey(n){return Z(this,null,function*(){let i=n.replace(/-----BEGIN PRIVATE KEY-----/,"").replace(/-----END PRIVATE KEY-----/,"").replace(/\s/g,""),s=atob(i),m=new Uint8Array(s.length);for(let r=0;r<s.length;r++)m[r]=s.charCodeAt(r);return yield crypto.subtle.importKey("pkcs8",m,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["sign"])})}ensureToken(){return Z(this,null,function*(){this.authOptions.authType==="serviceAccount"&&(yield this.getAccessToken());})}getDefaultHeaders(){return P(b({},super.getDefaultHeaders()),{Authorization:`Bearer ${this.accessToken}`})}getCompleteChatHeaders(n,i,s){return Z(this,null,function*(){return yield this.ensureToken(),this.getDefaultHeaders()})}getStreamChatHeaders(n,i,s){return Z(this,null,function*(){return yield this.ensureToken(),this.getDefaultHeaders()})}getModelPricing(){if(!(this.modelName in T))throw new H({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return T[this.modelName]}};var uo="gemini-1.5-flash-001",go=P(b({},De),{price:T[uo]}),Ki=v,tt=class extends M{constructor(t){super(go,t);}};var ho="gemini-1.5-flash-002",fo=P(b({},$e),{price:T[ho]}),Yi=v,ot=class extends M{constructor(t){super(fo,t);}};var yo="gemini-1.5-flash",bo=P(b({},Ae),{price:T[yo]}),Wi=v,nt=class extends M{constructor(t){super(bo,t);}};var To="gemini-1.5-pro-001",Po=P(b({},qe),{price:T[To]}),Ji=v,it=class extends M{constructor(t){super(Po,t);}};var Mo="gemini-1.5-pro-002",vo=P(b({},ze),{price:T[Mo]}),Xi=v,at=class extends M{constructor(t){super(vo,t);}};var ko="gemini-1.5-pro",_o=P(b({},Ve),{price:T[ko]}),Zi=v,st=class extends M{constructor(t){super(_o,t);}};var xo="gemini-1.5-flash-latest",So=P(b({},Be),{price:T[xo]}),Qi=v,rt=class extends M{constructor(t){super(So,t);}};var Eo="gemini-1.5-pro-latest",Co=P(b({},He),{price:T[Eo]}),ea=v,lt=class extends M{constructor(t){super(Co,t);}};var wo="gemini-2.0-flash-exp",Oo=P(b({},Di),{price:T[wo]}),ta=v,mt=class extends M{constructor(t){super(Oo,t);}};var Go="gemini-2.0-flash",Ro=P(b({},Ke),{price:T[Go]}),oa=v,dt=class extends M{constructor(t){super(Ro,t);}};var Io="gemini-2.5-flash-lite",jo=P(b({},Ye),{price:T[Io]}),na=v,ct=class extends M{constructor(t){super(jo,t);}};var Fo="gemini-2.5-flash-preview-04-17",Lo=P(b({},We),{price:T[Fo]}),ia=v,pt=class extends M{constructor(t){super(Lo,t);}};var No="gemini-2.5-flash",Uo=P(b({},Je),{price:T[No]}),aa=v,ut=class extends M{constructor(t){super(Uo,t);}};var Do="gemini-2.5-pro-preview-03-25",$o=P(b({},Xe),{price:T[Do]}),sa=v,gt=class extends M{constructor(t){super($o,t);}};var Bo="gemini-2.5-pro",Ao=P(b({},Ze),{price:T[Bo]}),ra=v,ht=class extends M{constructor(t){super(Ao,t);}};var qo="gemini-3-flash-preview",zo=P(b({},Qe),{price:T[qo]}),la=v,ft=class extends M{constructor(t){super(zo,t);}};var Ho="gemini-3-pro-preview",Vo=P(b({},et),{price:T[Ho]}),ma=v,yt=class extends M{constructor(t){super(Vo,t);}};var ce=[A],pe=zod.z.enum([A]);var ga=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 ha=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 se=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()}),te=class{constructor(t,n){this.version="v1";let i=se.parse(n);this.modelSchema=t,this.modelName=i.modelName,this.accessToken=i.accessToken;let s;if(i.baseUrl)s=i.baseUrl;else if(i.location&&i.projectId)s=fe.baseUrl(i.location,i.projectId,i.publisher);else throw new ke({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(t){return {shouldRetry:!1,delayMs:0}}getTokenCount(t){return t.requests.reduce((n,i)=>n+i.length,0)}transformModelRequest(t){var l,p,h,y;let n=ha.safeParse(t);if(!n.success)throw new ie({info:"Invalid model request",cause:n.error});let i=n.data,s=i.model,m={autoTruncate:((l=i.parameters)==null?void 0:l.auto_truncate)||((p=i.parameters)==null?void 0:p.autoTruncate),dimensions:((h=i.parameters)==null?void 0:h.output_dimensionality)||((y=i.parameters)==null?void 0:y.outputDimensionality)},r=Ce().parse(Ge(m)),d={modality:A,requests:i.instances.map(u=>u.content)};return {modelName:s,config:r,embeddingRequests:d}}transformConfig(t,n){let i=this.modelSchema.config.schema.safeParse(t);if(!i.success)throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let s=i.data;return Object.keys(s).forEach(r=>{if(!this.modelSchema.config.def[r])throw new V({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${r}',
19
+ available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),{parameters:Object.keys(s).reduce((r,d)=>{let p=this.modelSchema.config.def[d].param,h=s[d];return r[p]=h,r},{})}}transformEmbeddingRequests(t){let n=Fe().safeParse(t);if(!n.success)throw new de({info:"Invalid embedding requests",cause:n.error});if(t.modality!==A)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${A}' modality is supported for model : '${this.modelName}'`)});return {instances:n.data.requests.map(s=>({content:s}))}}getGetEmbeddingsUrl(t,n){return Z(this,null,function*(){return new Promise(i=>{i(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(t,n){return Z(this,null,function*(){return new Promise(i=>{i(this.getDefaultHeaders());})})}getGetEmbeddingsData(t,n){return Z(this,null,function*(){return new Promise(i=>{if(n.requests.length===0)throw new de({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});i(b(b(b({},this.getDefaultParams()),this.transformConfig(t)),this.transformEmbeddingRequests(n)));})})}transformGetEmbeddingsResponse(t){let n=ga.safeParse(t);if(n.success){let s=n.data.predictions.map((m,r)=>({index:r,embedding:m.embeddings.values}));return {encodingFormat:we,embeddings:s}}throw new H({info:"Invalid response from model",cause:n.error})}};var tn=e=>W({param:"output_dimensionality",title:_e.DIMENSIONS.title,description:_e.DIMENSIONS.description,min:1,max:e,step:1,default:e}),on=Oe({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 fa=e=>zod.z.object({dimensions:tn(e).schema,autoTruncate:on.schema}),ya=e=>({dimensions:tn(e).def,autoTruncate:on.def});var K={base:e=>({def:ya(e),schema:fa(e)})};var Ko="text-embedding-004",om="text-embedding-004",Yo=J(pe).parse({name:Ko,description:om,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),da=se,bt=class extends te{constructor(t){super(Yo,t);}};var Wo="text-multilingual-embedding-002",nm="text-multilingual-embedding-002",Jo=J(pe).parse({name:Wo,description:nm,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),ca=se,Tt=class extends te{constructor(t){super(Jo,t);}};var Xo="textembedding-gecko-multilingual@001",im="textembedding-gecko-multilingual@001",Zo=J(pe).parse({name:Xo,description:im,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),pa=se,Pt=class extends te{constructor(t){super(Zo,t);}};var Qo="textembedding-gecko@003",am="textembedding-gecko@003",en=J(pe).parse({name:Qo,description:am,modalities:ce,maxInputTokens:2048,maxOutputTokens:768,config:{def:K.base(768).def,schema:K.base(768).schema}}),ua=se,Mt=class extends te{constructor(t){super(en,t);}};
20
20
 
21
21
  exports.BaseChatModelOptions = v;
22
22
  exports.BaseChatModelVertex = M;
@@ -58,8 +58,8 @@ exports.Gemini2_0Flash = dt;
58
58
  exports.Gemini2_0FlashExp = mt;
59
59
  exports.Gemini2_0FlashExpLiteral = wo;
60
60
  exports.Gemini2_0FlashExpOptions = ta;
61
- exports.Gemini2_0FlashExpSchema = Go;
62
- exports.Gemini2_0FlashLiteral = Oo;
61
+ exports.Gemini2_0FlashExpSchema = Oo;
62
+ exports.Gemini2_0FlashLiteral = Go;
63
63
  exports.Gemini2_0FlashOptions = oa;
64
64
  exports.Gemini2_0FlashSchema = Ro;
65
65
  exports.Gemini2_5Flash = ut;
@@ -85,9 +85,9 @@ exports.Gemini2_5ProSchema = Ao;
85
85
  exports.Gemini3FlashPreview = ft;
86
86
  exports.Gemini3FlashPreviewLiteral = qo;
87
87
  exports.Gemini3FlashPreviewOptions = la;
88
- exports.Gemini3FlashPreviewSchema = Ho;
88
+ exports.Gemini3FlashPreviewSchema = zo;
89
89
  exports.Gemini3ProPreview = yt;
90
- exports.Gemini3ProPreviewLiteral = zo;
90
+ exports.Gemini3ProPreviewLiteral = Ho;
91
91
  exports.Gemini3ProPreviewOptions = ma;
92
92
  exports.Gemini3ProPreviewSchema = Vo;
93
93
  exports.Text_Embedding_004 = bt;