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