@adaline/google
Version:
Adaline Google
15 lines (13 loc) • 67.4 kB
JavaScript
'use strict';
var zod = require('zod');
var provider = require('@adaline/provider');
var types = require('@adaline/types');
var Kt=Object.defineProperty,Yt=Object.defineProperties;var Vt=Object.getOwnPropertyDescriptors;var Io=Object.getOwnPropertySymbols;var Wt=Object.prototype.hasOwnProperty,Jt=Object.prototype.propertyIsEnumerable;var te=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),Xt=r=>{throw TypeError(r)};var Lo=(r,e,o)=>e in r?Kt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):r[e]=o,E=(r,e)=>{for(var o in e||(e={}))Wt.call(e,o)&&Lo(r,o,e[o]);if(Io)for(var o of Io(e))Jt.call(e,o)&&Lo(r,o,e[o]);return r},D=(r,e)=>Yt(r,Vt(e));var R=(r,e,o)=>new Promise((t,a)=>{var d=i=>{try{n(o.next(i));}catch(s){a(s);}},l=i=>{try{n(o.throw(i));}catch(s){a(s);}},n=i=>i.done?t(i.value):Promise.resolve(i.value).then(d,l);n((o=o.apply(r,e)).next());}),No=function(r,e){this[0]=r,this[1]=e;},We=(r,e,o)=>{var t=(l,n,i,s)=>{try{var c=o[l](n),h=(n=c.value)instanceof No,T=c.done;Promise.resolve(h?n[0]:n).then(p=>h?t(l==="return"?l:"next",n[1]?{done:p.done,value:p.value}:p,i,s):i({value:p,done:T})).catch(p=>t("throw",p,i,s));}catch(p){s(p);}},a=l=>d[l]=n=>new Promise((i,s)=>t(l,n,i,s)),d={};return o=o.apply(r,e),d[te("asyncIterator")]=()=>d,a("next"),a("throw"),a("return"),d},Do=r=>{var e=r[te("asyncIterator")],o=!1,t,a={};return e==null?(e=r[te("iterator")](),t=d=>a[d]=l=>e[d](l)):(e=e.call(r),t=d=>a[d]=l=>{if(o){if(o=!1,d==="throw")throw l;return l}return o=!0,{done:!1,value:new No(new Promise(n=>{var i=e[d](l);i instanceof Object||Xt("Object expected"),n(i);}),1)}}),a[te("iterator")]=()=>a,t("next"),"throw"in e?t("throw"):a.throw=d=>{throw d},"return"in e&&t("return"),a};var en=["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"],on=["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"],Ao=(r,e)=>r.replace(e,"").replace(/_/g," ").toLowerCase().replace(/\b\w/g,o=>o.toUpperCase()),tn=en.map(r=>({value:r,label:Ao(r,"HARM_CATEGORY_")})),nn=on.map(r=>({value:r,label:Ao(r,"HARM_BLOCK_THRESHOLD_")})),Je=(r,e)=>provider.RangeConfigItem({param:"temperature",title:provider.CHAT_CONFIG.TEMPERATURE.title,description:provider.CHAT_CONFIG.TEMPERATURE.description,min:0,max:r,step:.01,default:e}),Xe=r=>provider.RangeConfigItem({param:"maxOutputTokens",title:provider.CHAT_CONFIG.MAX_TOKENS.title,description:provider.CHAT_CONFIG.MAX_TOKENS.description,min:0,max:r,step:1,default:0}),Qe=r=>provider.MultiStringConfigItem({param:"stopSequences",title:provider.CHAT_CONFIG.STOP(r).title,description:provider.CHAT_CONFIG.STOP(r).description,max:r}),Ze=r=>provider.RangeConfigItem({param:"topP",title:provider.CHAT_CONFIG.TOP_P.title,description:provider.CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:r}),ji=r=>provider.RangeConfigItem({param:"topK",title:provider.CHAT_CONFIG.TOP_K.title,description:provider.CHAT_CONFIG.TOP_K.description,min:1,max:40,step:1,default:r}),Bi=provider.RangeConfigItem({param:"frequencyPenalty",title:provider.CHAT_CONFIG.FREQUENCY_PENALTY.title,description:provider.CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),zi=provider.RangeConfigItem({param:"presencePenalty",title:provider.CHAT_CONFIG.PRESENCE_PENALTY.title,description:provider.CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),qi=provider.RangeConfigItem({param:"seed",title:provider.CHAT_CONFIG.SEED.title,description:provider.CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),eo=provider.SelectStringConfigItem({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"]}),oo=provider.PairedSelectConfigItem({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:tn},{key:"threshold",label:"Threshold",choices:nn}],uniqueByField:"category"}),to=provider.SelectBooleanConfigItem({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}),no=(r,e)=>provider.RangeConfigItem({param:"thinkingBudget",title:"Thinking budget",description:"Specify the total tokens for thinking (or reasoning), where one token approximates four English characters.",min:r,max:e,step:1,default:0}),io=provider.SelectStringConfigItem({param:"thinkingLevel",title:"Thinking Level",description:"Controls the depth of the model's reasoning process. Higher levels may result in more thorough reasoning but use more tokens.",default:"LOW",choices:["LOW","HIGH"]}),so=provider.SelectBooleanConfigItem({param:"googleSearch",title:"Google Search Tool",description:"Controls whether the model is allowed to use the Google Search tool. Powered by Google.",default:!1});var ne=(r,e,o,t,a)=>zod.z.object({temperature:Je(r,e).schema,maxTokens:Xe(o).schema,stop:Qe(t).schema,topP:Ze(a).schema,toolChoice:eo.schema,safetySettings:oo.schema,googleSearchTool:so.schema}),ie=(r,e,o,t,a)=>({temperature:Je(r,e).def,maxTokens:Xe(o).def,stop:Qe(t).def,topP:Ze(a).def,toolChoice:eo.def,safetySettings:oo.def,googleSearchTool:so.def});var jo=provider.ObjectSchemaConfigItem({param:"response_schema",title:provider.CHAT_CONFIG.RESPONSE_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:types.ResponseSchema}),Bo=provider.SelectStringConfigItem({param:"response_format",title:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_FORMAT_WITH_SCHEMA.description,default:"text",choices:["text","json_schema"]}),ae=(r,e,o,t,a)=>D(E({},ie(r,e,o,t,a)),{responseFormat:Bo.def,responseSchema:jo.def}),re=(r,e,o,t,a)=>ne(r,e,o,t,a).extend({responseFormat:Bo.schema,responseSchema:jo.schema});var zo=(r,e,o,t,a,d,l)=>re(r,e,o,t,a).extend({reasoningEnabled:to.schema,maxReasoningTokens:no(d,l).schema,reasoningEffort:io.schema}),qo=(r,e,o,t,a,d,l)=>D(E({},ae(r,e,o,t,a)),{reasoningEnabled:to.def,maxReasoningTokens:no(d,l).def,reasoningEffort:io.def});var ao=r=>provider.RangeConfigItem({param:"outputDimensionality",title:provider.EMBEDDING_CONFIG.DIMENSIONS.title,description:provider.EMBEDDING_CONFIG.DIMENSIONS.description,min:1,max:r,step:1,default:r});var Ko=r=>zod.z.object({dimensions:ao(r).schema}),Yo=r=>({dimensions:ao(r).def});var u={base:(r,e,o,t,a)=>({def:ie(r,e,o,t,a),schema:ne(r,e,o,t,a)}),responseSchema:(r,e,o,t,a)=>({def:ae(r,e,o,t,a),schema:re(r,e,o,t,a)}),reasoning:(r,e,o,t,a,d,l)=>({def:qo(r,e,o,t,a,d,l),schema:zo(r,e,o,t,a,d,l)})},q={base:r=>({def:Yo(r),schema:Ko(r)})};var pn="google",B=class{constructor(){this.version="v1";this.name=pn;this.chatModelFactories={[le]:{model:me,modelOptions:Wo,modelSchema:ro},[de]:{model:pe,modelOptions:Jo,modelSchema:lo},[ce]:{model:ge,modelOptions:Xo,modelSchema:mo},[he]:{model:fe,modelOptions:Qo,modelSchema:po},[ue]:{model:ye,modelOptions:Zo,modelSchema:co},[Ce]:{model:Te,modelOptions:et,modelSchema:go},[Me]:{model:Ge,modelOptions:ot,modelSchema:ho},[be]:{model:Pe,modelOptions:tt,modelSchema:fo},[_e]:{model:Se,modelOptions:nt,modelSchema:uo},[Oe]:{model:ke,modelOptions:st,modelSchema:Co},[ve]:{model:Fe,modelOptions:rt,modelSchema:Mo},[Re]:{model:xe,modelOptions:at,modelSchema:To},[Ie]:{model:Le,modelOptions:lt,modelSchema:Go},[Ne]:{model:De,modelOptions:mt,modelSchema:bo},[Ue]:{model:$e,modelOptions:dt,modelSchema:Po},[Ee]:{model:we,modelOptions:it,modelSchema:yo}};this.embeddingModelFactories={[_o]:{model:Ae,modelOptions:pt,modelSchema:So},[Eo]:{model:je,modelOptions:ct,modelSchema:wo}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,o)=>(e[o]=this.chatModelFactories[o].modelSchema,e),{})}chatModel(e){let o=e.modelName;if(!(o in this.chatModelFactories))throw new provider.ProviderError({info:`Google chat model: ${o} not found`,cause:new Error(`Google chat model: ${o} not found, available chat models:
[${this.chatModelLiterals().join(", ")}]`)});let t=this.chatModelFactories[o].model,a=this.chatModelFactories[o].modelOptions.parse(e);return new t(a)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,o)=>(e[o]=this.embeddingModelFactories[o].modelSchema,e),{})}embeddingModel(e){let o=e.modelName;if(!(o in this.embeddingModelFactories))throw new provider.ProviderError({info:`Google embedding model: ${o} not found`,cause:new Error(`Google embedding model: ${o} not found, available embedding models:
[${this.embeddingModelLiterals().join(", ")}]`)});let t=this.embeddingModelFactories[o].model,a=this.embeddingModelFactories[o].modelOptions.parse(e);return new t(a)}};B.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}}}]},"gemini-3-flash-preview":{modelName:"gemini-3-flash-preview",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.5,outputPricePerMillion:3}}}]}};var b=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),yn="model",Cn="function",P={system:types.UserRoleLiteral,user:types.UserRoleLiteral,assistant:yn,tool:Cn};var _=[types.TextModalityLiteral,types.ImageModalityLiteral,types.PdfModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral,types.ReasoningModalityLiteral,types.SearchResultModalityLiteral,types.ErrorModalityLiteral],S=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.PdfModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral,types.ReasoningModalityLiteral,types.SearchResultModalityLiteral,types.ErrorModalityLiteral]),Es=[types.TextModalityLiteral],ws=zod.z.enum([types.TextModalityLiteral]),Os=[types.TextModalityLiteral,types.ImageModalityLiteral],ks=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral]),Rs=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],xs=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var Tn=zod.z.object({renderedContent:zod.z.string().optional()}),Mn=zod.z.object({uri:zod.z.string().optional(),title:zod.z.string().optional()}),Gn=zod.z.object({web:Mn.optional()}),bn=zod.z.object({startIndex:zod.z.number().optional(),endIndex:zod.z.number().optional(),text:zod.z.string().optional()}),Pn=zod.z.object({segment:bn.optional(),groundingChunkIndices:zod.z.array(zod.z.number()).optional(),confidenceScores:zod.z.array(zod.z.number()).optional()}),yt=zod.z.object({searchEntryPoint:Tn.optional(),groundingChunks:zod.z.array(Gn).optional(),groundingSupports:zod.z.array(Pn).optional(),webSearchQueries:zod.z.array(zod.z.string()).optional()}),_n=zod.z.object({text:zod.z.string(),thought:zod.z.boolean().optional()}),Sn=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())}),thoughtSignature:zod.z.string().optional()}),Ct=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([_n,Sn]))}).optional(),finishReason:zod.z.string(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()}))),groundingMetadata:yt.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()}),En=zod.z.object({text:zod.z.string(),thought:zod.z.boolean().optional()}),wn=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())}),thoughtSignature:zod.z.string().optional()}),ko=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([En,wn]))}).optional(),finishReason:zod.z.string().optional(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()}))),groundingMetadata:yt.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()});var _t=zod.z.object({text:zod.z.string().min(1)}),On=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),kn=zod.z.object({file_data:zod.z.object({mime_type:zod.z.string().min(1),file_uri:zod.z.string().min(1)})}),Rn=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))}),thought_signature:zod.z.string().optional()}),xn=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),Tt=zod.z.object({text:zod.z.string(),thought:zod.z.literal(!0),thought_signature:zod.z.string().min(1)}),vn=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([_t,On,kn,Rn,xn,Tt,Tt]))}),Mt=zod.z.object({parts:zod.z.array(_t)}),Fn=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),In=zod.z.object({timeRangeFilter:zod.z.object({startTime:zod.z.string().datetime().optional(),endTime:zod.z.string().datetime().optional()}).optional()}),Gt=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()})}),Ln=zod.z.object({thinkingBudget:zod.z.number().optional(),includeThoughts:zod.z.boolean().optional(),thinkingLevel:zod.z.enum(["LOW","HIGH"]).optional()}),bt=zod.z.object({stopSequences:zod.z.array(zod.z.string()).optional(),maxOutputTokens:zod.z.number().optional(),temperature:zod.z.number().optional(),topP:zod.z.number().optional(),topK:zod.z.number().optional(),presencePenalty:zod.z.number().optional(),frequencyPenalty:zod.z.number().optional(),seed:zod.z.number().optional(),thinkingConfig:Ln.optional()}),Pt=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"])}),St=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(vn),systemInstruction:Mt.optional(),system_instruction:Mt.optional(),generationConfig:bt.optional(),generation_config:bt.optional(),safetySettings:zod.z.array(Pt).optional(),safety_settings:zod.z.array(Pt).optional(),tools:zod.z.object({function_declarations:zod.z.array(Fn),google_search:In.optional()}).optional(),toolConfig:Gt.optional(),tool_config:Gt.optional()});var G=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()}),M=class{constructor(e,o){this.version="v1";var a;let t=G.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash((a=t.baseUrl)!=null?a:B.baseUrl),this.completeChatUrl=provider.urlWithoutTrailingSlash(t.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=provider.urlWithoutTrailingSlash(t.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(e,o){var l;let a=0,d=n=>{let i=n.match(/^(\d+(?:\.\d+)?)s$/);return i?Math.ceil(parseFloat(i[1])*1e3):0};if(o&&typeof o=="object"){let n=o;if((l=n.error)!=null&&l.details&&Array.isArray(n.error.details)){let i=n.error.details.find(s=>s["@type"]==="type.googleapis.com/google.rpc.RetryInfo");i!=null&&i.retryDelay&&(a=d(i.retryDelay));}}return {shouldRetry:!0,delayMs:a}}getTokenCount(e){return e.reduce((o,t)=>o+t.content.map(a=>a.modality==="text"?a.value:"").join(" ").length,0)}transformPdfMessages(e){return R(this,null,function*(){let o=n=>R(this,null,function*(){let i={};provider.isRunningInBrowser()||(i["User-Agent"]="Mozilla/5.0 (compatible; GoogleFilesAPI/1.0)");let s=yield fetch(n,{headers:i});if(!s.ok)throw new provider.InvalidMessagesError({info:`Failed to download PDF from URL: ${n}`,cause:new Error(`HTTP ${s.status}: ${s.statusText}`)});let c=yield s.arrayBuffer();return new Uint8Array(c)}),t=n=>R(this,null,function*(){try{let i=yield fetch(`https://generativelanguage.googleapis.com/v1beta/files?key=${this.apiKey}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok)return null;let h=((yield i.json()).files||[]).find(T=>T.displayName===n);return h?h.uri:null}catch(i){return null}}),a=(n,i)=>R(this,null,function*(){let s=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":n.length.toString(),"X-Goog-Upload-Header-Content-Type":"application/pdf","Content-Type":"application/json"},body:JSON.stringify({file:{display_name:i}})});if(!s.ok)throw new provider.InvalidMessagesError({info:"Failed to start PDF upload to Google Files API",cause:new Error(`HTTP ${s.status}: ${s.statusText}`)});let c=s.headers.get("x-goog-upload-url");if(!c)throw new provider.InvalidMessagesError({info:"No upload URL received from Google Files API",cause:new Error("Missing x-goog-upload-url header")});let h={"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"};provider.isRunningInBrowser()||(h["Content-Length"]=n.length.toString());let T=yield fetch(c,{method:"POST",headers:h,body:n});if(!T.ok)throw new provider.InvalidMessagesError({info:"Failed to upload PDF content to Google Files API",cause:new Error(`HTTP ${T.status}: ${T.statusText}`)});return (yield T.json()).file.uri}),d=n=>R(this,null,function*(){let i=yield t(n.file.id);if(i)return i;let s;if(n.value.type==="url")s=yield o(n.value.url);else {let c=n.value.base64,h="data:application/pdf;base64,";c=c.startsWith(h)?c.substring(h.length):c,s=provider.convertBase64ToUint8Array(c);}return yield a(s,n.file.id)}),l=[];for(let n of e){let i=[];for(let s of n.content)if(s.modality===types.PdfModalityLiteral){let c=yield d(s);i.push(D(E({},s),{value:{type:"url",url:c}}));}else i.push(s);l.push(D(E({},n),{content:i}));}return l})}transformModelRequest(e){let o=St.safeParse(e);if(!o.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,a=t.model;if(t.system_instruction&&t.systemInstruction)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'system_instruction' and 'systemInstruction' are not allowed at the same time")});if(t.generation_config&&t.generationConfig)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'generation_config' and 'generationConfig' are not allowed at the same time")});if(t.tool_config&&t.toolConfig)throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let d=t.system_instruction||t.systemInstruction,l=t.generation_config||t.generationConfig,n=t.safety_settings||t.safetySettings,i=t.tool_config||t.toolConfig;if(i&&(!t.tools||t.tools.function_declarations.length===0))throw new provider.InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let s={};i&&(i.function_calling_config.mode==="ANY"&&i.function_calling_config.allowed_function_names&&i.function_calling_config.allowed_function_names.length===1?s.toolChoice=i.function_calling_config.allowed_function_names[0]:s.toolChoice=i.function_calling_config.mode.toLowerCase()),s.seed=l==null?void 0:l.seed,s.maxTokens=l==null?void 0:l.maxOutputTokens,s.temperature=l==null?void 0:l.temperature,s.topP=l==null?void 0:l.topP,s.presencePenalty=l==null?void 0:l.presencePenalty,s.frequencyPenalty=l==null?void 0:l.frequencyPenalty,s.stop=l==null?void 0:l.stopSequences,s.safetySettings=n;let c=types.Config().parse(provider.removeUndefinedEntries(s)),h=[];d&&d.parts.forEach(p=>{h.push({role:types.SystemRoleLiteral,content:[{modality:types.TextModalityLiteral,value:p.text}]});}),t.contents.forEach(p=>{let f=p.role;switch(f){case"user":{let O=p.parts.map(w=>"text"in w?{modality:types.TextModalityLiteral,value:w.text}:{modality:types.ImageModalityLiteral,detail:"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:w.inline_data.data,mediaType:w.inline_data.mime_type.split("/")[1]}});h.push({role:f,content:O});}break;case"model":{let O=p.parts.map((w,k)=>"text"in w?{modality:types.TextModalityLiteral,value:w.text}:{modality:types.ToolCallModalityLiteral,id:k.toString(),index:k,name:w.function_call.name,arguments:JSON.stringify(w.function_call.args)});h.push({role:types.AssistantRoleLiteral,content:O});}break;case"function":{let O=p.parts.map((w,k)=>({modality:types.ToolResponseModalityLiteral,id:k.toString(),index:k,name:w.function_response.name,data:JSON.stringify(w.function_response.response)}));h.push({role:types.ToolRoleLiteral,content:O});}break;default:throw new provider.InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${p.role}' is not supported for model : ${this.modelName}`)})}});let T=[];return t.tools&&t.tools.function_declarations.forEach(p=>{T.push({type:"function",definition:{schema:{name:p.name,description:p.description,parameters:p.parameters}}});}),{modelName:a,config:c,messages:h,tools:T.length>0?T:void 0}}transformConfig(e,o,t){let a=e.toolChoice;delete e.toolChoice;let d=this.modelSchema.config.schema.safeParse(e);if(!d.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:d.error});let l=d.data;Object.keys(l).forEach(c=>{if(!(c in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${c}',
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let n=Object.keys(l).reduce((c,h)=>{let T=this.modelSchema.config.def[h],p=T.param,f=l[h];return h==="reasoningEnabled"?c.thinkingConfig=c.thinkingConfig&&typeof c.thinkingConfig=="object"?D(E({},c.thinkingConfig),{includeThoughts:f}):{includeThoughts:f}:h==="maxReasoningTokens"?c.thinkingConfig=c.thinkingConfig&&typeof c.thinkingConfig=="object"?D(E({},c.thinkingConfig),{thinkingBudget:f}):{thinkingBudget:f}:h==="reasoningEffort"?c.thinkingConfig=c.thinkingConfig&&typeof c.thinkingConfig=="object"?D(E({},c.thinkingConfig),{thinkingLevel:f}):{thinkingLevel:f}:p==="maxOutputTokens"&&T.type==="range"&&f===0?c[p]=T.max:c[p]=f,c},{});if(n.thinkingConfig&&typeof n.thinkingConfig=="object"&&"thinkingBudget"in n.thinkingConfig&&"thinkingLevel"in n.thinkingConfig&&n.thinkingConfig.thinkingBudget!==void 0&&n.thinkingConfig.thinkingBudget!==0&&n.thinkingConfig.thinkingLevel!==void 0)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("Only one of 'thinkingBudget' or 'thinkingLevel' can be set, not both.")});let i=n.safetySettings;delete n.safetySettings,delete n.googleSearch;let s;if(a!==void 0){let c=a;if(!t||t&&t.length===0)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(t&&t.length>0){let h=this.modelSchema.config.def.toolChoice;if(h.choices.includes(c))c==="any"?s={function_calling_config:{mode:"ANY",allowed_function_names:t.map(T=>T.definition.schema.name)}}:s={function_calling_config:{mode:c.toUpperCase()}};else if(t.map(T=>T.definition.schema.name).includes(c))s={function_calling_config:{mode:"ANY",allowed_function_names:[c]}};else throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${c}' is not part of provided 'tools' names or
one of [${h.choices.join(", ")}]`)})}}if("response_format"in n&&n.response_format!==void 0){let c=n.response_format;if(c==="json_schema"){let h=n.response_schema;if(!("response_schema"in n)||!n.response_schema||!(h!=null&&h.schema))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'responseSchema' is required in config when 'responseFormat' is 'json_schema'")});n.responseSchema=h.schema,n.responseMimeType="application/json","additionalProperties"in h.schema&&delete n.responseSchema.additionalProperties,delete n.response_format,delete n.response_schema;}else c==="json_object"?(n.responseSchema={type:"object"},delete n.response_format):c==="text"&&delete n.response_format;}return E(E({generation_config:n},s?{tool_config:s}:{}),i?{safety_settings:i}:{})}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let o=n=>{let i=n.match(/^data:(image\/[a-zA-Z]+|application\/pdf);base64,/);return i?n.substring(i[0].length):n},t=e.map(n=>{let i=types.Message().safeParse(n);if(!i.success)throw new provider.InvalidMessagesError({info:"Invalid messages",cause:i.error});return i.data});t.forEach(n=>{n.content.forEach(i=>{if(!this.modelSchema.modalities.includes(i.modality))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${i.modality}',
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(n=>{if(!Object.keys(this.modelSchema.roles).includes(n.role))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${n.role}',
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}),t.forEach(n=>{n.content=n.content.filter(i=>i.modality!=="error"&&i.modality!=="search-result");});let a={parts:[]},d=[];if(t.forEach(n=>{switch(n.role){case types.SystemRoleLiteral:n.content.forEach(i=>{if(i.modality===types.TextModalityLiteral)a.parts.push({text:i.value});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${i.modality}'`)})});break;case types.AssistantRoleLiteral:{let i=[];n.content.forEach(s=>{if(s.modality===types.TextModalityLiteral)i.push({text:s.value});else if(s.modality===types.ToolCallModalityLiteral)i.push(E({function_call:{name:s.name,args:JSON.parse(s.arguments)}},s.thoughtSignature?{thought_signature:s.thoughtSignature}:{}));else if(s.modality===types.ReasoningModalityLiteral)s.value.type==="thinking"&&s.value.thinking&&i.push({text:s.value.thinking,thought:!0,thought_signature:s.value.signature});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${s.modality}'`)})}),d.push({role:this.modelSchema.roles[n.role],parts:i});}break;case types.UserRoleLiteral:{let i=[];n.content.forEach(s=>{if(s.modality===types.TextModalityLiteral)i.push({text:s.value});else if(s.modality===types.ImageModalityLiteral){if(s.value.type==="base64"){let c=s.value.base64;c=o(c),i.push({inline_data:{mime_type:`image/${s.value.mediaType}`,data:c}});}else if(s.value.type==="url")throw new provider.InvalidMessagesError({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${s.value.type}'`)})}else if(s.modality===types.PdfModalityLiteral)if(s.value.type==="base64"){let c=s.value.base64;c=o(c),i.push({inline_data:{mime_type:"application/pdf",data:c}});}else s.value.type==="url"&&i.push({file_data:{mime_type:"application/pdf",file_uri:s.value.url}});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${s.modality}'`)})}),d.push({role:this.modelSchema.roles[n.role],parts:i});}break;case types.ToolRoleLiteral:{let i=[];n.content.forEach(s=>{if(s.modality===types.ToolResponseModalityLiteral)i.push({function_response:{name:s.name,response:JSON.parse(s.data)}});else throw new provider.InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${s.modality}'`)})}),d.push({role:this.modelSchema.roles[n.role],parts:i});}break;default:throw new provider.InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' is not supported,
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),d[0].role!==this.modelSchema.roles[types.UserRoleLiteral])throw new provider.InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});let l=n=>n===this.modelSchema.roles[types.UserRoleLiteral]||n===this.modelSchema.roles[types.ToolRoleLiteral]?[this.modelSchema.roles[types.AssistantRoleLiteral]]:[this.modelSchema.roles[types.UserRoleLiteral],this.modelSchema.roles[types.ToolRoleLiteral]];for(let n=1;n<d.length;n++)if(!l(d[n-1].role).includes(d[n].role))throw new provider.InvalidMessagesError({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${d[n].role}' after message with role : '${d[n-1].role}'`)});if(d[d.length-1].role!==this.modelSchema.roles[types.UserRoleLiteral]&&d[d.length-1].role!==this.modelSchema.roles[types.ToolRoleLiteral])throw new provider.InvalidMessagesError({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires last message to be from user`)});return E({contents:d},a.parts.length>0?{system_instruction:a}:{})}stripAdditionalProperties(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(t=>this.stripAdditionalProperties(t));let o={};for(let[t,a]of Object.entries(e))t!=="additionalProperties"&&(o[t]=this.stripAdditionalProperties(a));return o}transformTools(e,o){if(!this.modelSchema.modalities.includes(types.ToolCallModalityLiteral))throw new provider.InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${types.ToolCallModalityLiteral}'`)});if((!e||e.length===0)&&!(o!=null&&o.googleSearchTool))return {tools:[]};let a=(e!=null?e:[]).map(d=>{let l=types.Tool().safeParse(d);if(!l.success)throw new provider.InvalidToolsError({info:"Invalid tools",cause:l.error});return l.data}).map(d=>({name:d.definition.schema.name,description:d.definition.schema.description,parameters:this.stripAdditionalProperties(d.definition.schema.parameters)}));return {tools:[E(E({},a.length>0?{function_declarations:a}:{}),o!=null&&o.googleSearchTool?{google_search:{}}:{})]}}getCompleteChatUrl(e,o,t){return R(this,null,function*(){return new Promise(a=>{a(this.completeChatUrl);})})}getCompleteChatHeaders(e,o,t){return R(this,null,function*(){return new Promise(a=>{a(this.getDefaultHeaders());})})}getCompleteChatData(e,o,t){return R(this,null,function*(){let a=this.transformConfig(e,o,t),d=yield this.transformPdfMessages(o),l=this.transformMessages(d);if(l.messages&&l.messages.length===0)throw new provider.InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let n=this.transformTools(t||[],e);return E(E(E(E({},this.getDefaultParams()),a),l),n)})}transformCompleteChatResponse(e){var t,a,d,l,n,i;let o=Ct.safeParse(e);if(o.success){if(o.data.candidates.length===0)throw new provider.ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(o.data)}`)});let s={messages:[],usage:void 0,logProbs:void 0},c=o.data;c.usageMetadata&&(s.usage={promptTokens:c.usageMetadata.promptTokenCount,totalTokens:c.usageMetadata.totalTokenCount,completionTokens:c.usageMetadata.candidatesTokenCount||0});let h=c.candidates[0];if(h.content){let p=h.content.parts.map((f,y)=>{if("text"in f&&f.text!==void 0)return f.thought===!0?types.createReasoningContent(f.text,""):types.createTextContent(f.text);if("functionCall"in f&&f.functionCall!==void 0)return types.createToolCallContent(y,`${f.functionCall.name}_${y}`,f.functionCall.name,JSON.stringify(f.functionCall.args),void 0,f.thoughtSignature)});s.messages.push({role:types.AssistantRoleLiteral,content:p});}h.groundingMetadata&&(s.messages.length===0?s.messages.push({role:types.AssistantRoleLiteral,content:[types.createSearchResultGoogleContent(((t=h.groundingMetadata.webSearchQueries)==null?void 0:t[0])||"",((a=h.groundingMetadata.groundingChunks)==null?void 0:a.map(p=>{var f,y;return {source:p.web?"web":"",url:((f=p.web)==null?void 0:f.uri)||"",title:((y=p.web)==null?void 0:y.title)||""}}))||[],((d=h.groundingMetadata.groundingSupports)==null?void 0:d.map(p=>{var f,y,O;return {text:((f=p.segment)==null?void 0:f.text)||"",responseIndices:p.groundingChunkIndices||[],startIndex:((y=p.segment)==null?void 0:y.startIndex)||void 0,endIndex:((O=p.segment)==null?void 0:O.endIndex)||void 0,confidenceScores:p.confidenceScores||void 0}}))||[])]}):s.messages[0].content.push(types.createSearchResultGoogleContent(((l=h.groundingMetadata.webSearchQueries)==null?void 0:l[0])||"",((n=h.groundingMetadata.groundingChunks)==null?void 0:n.map(p=>{var f,y;return {source:p.web?"web":"",url:((f=p.web)==null?void 0:f.uri)||"",title:((y=p.web)==null?void 0:y.title)||""}}))||[],((i=h.groundingMetadata.groundingSupports)==null?void 0:i.map(p=>{var f,y,O;return {text:((f=p.segment)==null?void 0:f.text)||"",responseIndices:p.groundingChunkIndices||[],startIndex:((y=p.segment)==null?void 0:y.startIndex)||void 0,endIndex:((O=p.segment)==null?void 0:O.endIndex)||void 0,confidenceScores:p.confidenceScores||void 0}}))||[])));let T=h.safetyRatings;if(T&&T.length>0&&T.forEach(p=>{p.blocked&&(s.messages.length===0?s.messages.push({role:types.AssistantRoleLiteral,content:[types.createSafetyErrorContent(p.category,p.probability,p.blocked,`Blocked content for category: ${p.category} with probability: ${p.probability}`)]}):s.messages[0].content.push(types.createSafetyErrorContent(p.category,p.probability,p.blocked,`Blocked content for category: ${p.category} with probability: ${p.probability}`)));}),s.messages.length>0)return s;if(s.messages.length===0&&h.finishReason==="SAFETY")throw new provider.ModelResponseError({info:"Blocked content, model response finished with safety reason",cause:new Error("Blocked content, model response finished with safety reason")})}throw new provider.ModelResponseError({info:"Invalid response from model",cause:o.error})}getStreamChatUrl(e,o,t){return R(this,null,function*(){return new Promise(a=>{a(this.streamChatUrl);})})}getStreamChatHeaders(e,o,t){return R(this,null,function*(){return new Promise(a=>{a(this.getDefaultHeaders());})})}getStreamChatData(e,o,t){return R(this,null,function*(){let a=this.transformConfig(e,o,t),d=yield this.transformPdfMessages(o),l=this.transformMessages(d);if(l.messages&&l.messages.length===0)throw new provider.InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let n=this.transformTools(t||[],e);return E(E(E(E({},this.getDefaultParams()),a),l),n)})}transformStreamChatResponseChunk(e,o){return We(this,null,function*(){var a,d,l;let t=(o+e).split(",\r").filter(n=>n.trim()!=="");for(let n of t){let i=n;if(i=i.replace(/\n/g,""),i.startsWith("[")||i.startsWith(",{"))i=i.slice(1);else if(i.endsWith("]")){if(i==="]")return;i=i.slice(0,-1);}let s;try{s=JSON.parse(i);}catch(h){if(h instanceof SyntaxError){o=i;continue}else throw h}o="";let c=ko.safeParse(s);if(c.success){let h={partialMessages:[]},T=c.data;if(T.candidates.length>0){let p=T.candidates[0].content;p&&"parts"in p&&p.parts.length>0&&p.parts.forEach((f,y)=>{if("text"in f&&f.text!==void 0&&(f.thought===!0?h.partialMessages.push(types.createPartialReasoningMessage(types.AssistantRoleLiteral,f.text,"")):h.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,f.text))),"functionCall"in f&&f.functionCall!==void 0){let O=f.functionCall;h.partialMessages.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,y,`${O.name}_${y}`,O.name,JSON.stringify(O.args),void 0,f.thoughtSignature));}});}if(T.usageMetadata&&(h.usage={promptTokens:T.usageMetadata.promptTokenCount,completionTokens:T.usageMetadata.candidatesTokenCount,totalTokens:T.usageMetadata.totalTokenCount}),T.candidates.length>0){let p=T.candidates[0];p.groundingMetadata&&h.partialMessages.push(types.createPartialSearchResultGoogleMessage(types.AssistantRoleLiteral,((a=p.groundingMetadata.webSearchQueries)==null?void 0:a[0])||"",((d=p.groundingMetadata.groundingChunks)==null?void 0:d.map(y=>{var O,w;return {source:y.web?"web":"",url:((O=y.web)==null?void 0:O.uri)||"",title:((w=y.web)==null?void 0:w.title)||""}}))||[],((l=p.groundingMetadata.groundingSupports)==null?void 0:l.map(y=>{var O,w,k;return {text:((O=y.segment)==null?void 0:O.text)||"",responseIndices:y.groundingChunkIndices||[],startIndex:((w=y.segment)==null?void 0:w.startIndex)||void 0,endIndex:((k=y.segment)==null?void 0:k.endIndex)||void 0,confidenceScores:y.confidenceScores||void 0}}))||[]));let f=p.safetyRatings;f&&f.length>0&&f.forEach(y=>{y.blocked&&h.partialMessages.push(types.createPartialSafetyErrorMessage(types.AssistantRoleLiteral,y.category,y.probability,y.blocked,`Blocked content for category: ${y.category} with probability: ${y.probability}`));});}yield {partialResponse:h,buffer:o};}else throw new provider.ModelResponseError({info:"Invalid response from model",cause:c.error})}yield {partialResponse:{partialMessages:[]},buffer:o};})}transformProxyStreamChatResponseChunk(e,o,t,a,d){return We(this,null,function*(){var c,h,T;if((d==null?void 0:d.alt)!=="sse"){yield*Do(this.transformStreamChatResponseChunk(e,o));return}let l=o+e,n=[],i="",s=0;for(;s<l.length;){let p=l.indexOf(`
`,s);if(p===-1){i=l.substring(s);break}else {let f=l.substring(s,p).trim();f&&n.push(f),s=p+1;}}for(let p of n){if(p==="data: [DONE]")return;if(p.startsWith("data: ")){let f=p.substring(6);try{let y=JSON.parse(f),O=ko.safeParse(y);if(O.success){let w={partialMessages:[]},k=O.data;if(k.candidates.length>0){let N=k.candidates[0].content;N&&"parts"in N&&N.parts.length>0&&N.parts.forEach((L,x)=>{if("text"in L&&L.text!==void 0&&(L.thought===!0?w.partialMessages.push(types.createPartialReasoningMessage(types.AssistantRoleLiteral,L.text,"")):w.partialMessages.push(types.createPartialTextMessage(types.AssistantRoleLiteral,L.text))),"functionCall"in L&&L.functionCall!==void 0){let $=L.functionCall;w.partialMessages.push(types.createPartialToolCallMessage(types.AssistantRoleLiteral,x,`${$.name}_${x}`,$.name,JSON.stringify($.args),void 0,L.thoughtSignature));}});}if(k.usageMetadata&&k.usageMetadata.totalTokenCount&&k.usageMetadata.promptTokenCount&&k.usageMetadata.candidatesTokenCount&&(w.usage={promptTokens:k.usageMetadata.promptTokenCount,completionTokens:k.usageMetadata.candidatesTokenCount,totalTokens:k.usageMetadata.totalTokenCount}),k.candidates.length>0){let N=k.candidates[0];N.groundingMetadata&&w.partialMessages.push(types.createPartialSearchResultGoogleMessage(types.AssistantRoleLiteral,((c=N.groundingMetadata.webSearchQueries)==null?void 0:c[0])||"",((h=N.groundingMetadata.groundingChunks)==null?void 0:h.map(x=>{var $,W;return {source:x.web?"web":"",url:(($=x.web)==null?void 0:$.uri)||"",title:((W=x.web)==null?void 0:W.title)||""}}))||[],((T=N.groundingMetadata.groundingSupports)==null?void 0:T.map(x=>{var $,W,Fo;return {text:(($=x.segment)==null?void 0:$.text)||"",responseIndices:x.groundingChunkIndices||[],startIndex:((W=x.segment)==null?void 0:W.startIndex)||void 0,endIndex:((Fo=x.segment)==null?void 0:Fo.endIndex)||void 0,confidenceScores:x.confidenceScores||void 0}}))||[]));let L=N.safetyRatings;L&&L.length>0&&L.forEach(x=>{x.blocked&&w.partialMessages.push(types.createPartialSafetyErrorMessage(types.AssistantRoleLiteral,x.category,x.probability,x.blocked,`Blocked content for category: ${x.category} with probability: ${x.probability}`));});}yield {partialResponse:w,buffer:o};}else throw new provider.ModelResponseError({info:"Invalid response from model",cause:O.error})}catch(y){throw new provider.ModelResponseError({info:`Malformed JSON received in stream: ${f}`,cause:y})}}}yield {partialResponse:{partialMessages:[]},buffer:i};})}getProxyCompleteChatUrl(e,o,t){return R(this,null,function*(){return new Promise(a=>{a(this.completeChatUrl);})})}getProxyStreamChatUrl(e,o,t){return R(this,null,function*(){return new Promise(a=>{if(!t||Object.keys(t).length===0){a(this.streamChatUrl);return}let d=new URL(this.streamChatUrl);Object.entries(t).forEach(([l,n])=>{n!=null&&d.searchParams.set(l,n);}),a(d.toString());})})}getProxyCompleteChatHeaders(e,o,t){return R(this,null,function*(){if(!o)return {};let a=E({},o);return delete a.host,delete a["content-length"],a})}getProxyStreamChatHeaders(e,o,t){return R(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,o,t)})}getModelPricing(){if(!(this.modelName in C))throw new provider.ModelResponseError({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return C[this.modelName]}};var le="gemini-1.5-flash-001",Yn="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",ro=provider.ChatModelSchema(b,S).parse({name:le,description:Yn,maxInputTokens:1e6,maxOutputTokens:8192,roles:P,modalities:_,config:{def:u.responseSchema(2,1,8192,4,.95).def,schema:u.responseSchema(2,1,8192,4,.95).schema},price:C[le]}),Wo=G,me=class extends M{constructor(e){super(ro,e);}};var de="gemini-1.5-flash-002",Wn="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",lo=provider.ChatModelSchema(b,S).parse({name:de,description:Wn,maxInputTokens:1e6,maxOutputTokens:8192,roles:P,modalities:_,config:{def:u.responseSchema(2,1,8192,4,.95).def,schema:u.responseSchema(2,1,8192,4,.95).schema},price:C[de]}),Jo=G,pe=class extends M{constructor(e){super(lo,e);}};var ce="gemini-1.5-flash-latest",Xn="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",mo=provider.ChatModelSchema(b,S).parse({name:ce,description:Xn,maxInputTokens:1e6,maxOutputTokens:8192,roles:P,modalities:_,config:{def:u.responseSchema(2,1,8192,4,.95).def,schema:u.responseSchema(2,1,8192,4,.95).schema},price:C[ce]}),Xo=G,ge=class extends M{constructor(e){super(mo,e);}};var he="gemini-1.5-flash",Zn="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",po=provider.ChatModelSchema(b,S)