@adaline/google 0.16.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +770 -82
- package/dist/index.d.ts +770 -82
- package/dist/index.js +146 -135
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -12
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import { z
|
|
2
|
-
import { RangeConfigItem, CHAT_CONFIG, SelectStringConfigItem, ObjectSchemaConfigItem, ChatModelSchema, EmbeddingModelSchema, MultiStringConfigItem, EMBEDDING_CONFIG, ProviderError, urlWithoutTrailingSlash, InvalidModelRequestError, removeUndefinedEntries, InvalidMessagesError, InvalidConfigError, InvalidToolsError, ModelResponseError, InvalidEmbeddingRequestsError } from '@adaline/provider';
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { RangeConfigItem, CHAT_CONFIG, SelectStringConfigItem, ObjectSchemaConfigItem, SelectBooleanConfigItem, ChatModelSchema, EmbeddingModelSchema, MultiStringConfigItem, EMBEDDING_CONFIG, ProviderError, urlWithoutTrailingSlash, InvalidModelRequestError, removeUndefinedEntries, InvalidMessagesError, InvalidConfigError, InvalidToolsError, ModelResponseError, InvalidEmbeddingRequestsError } from '@adaline/provider';
|
|
3
3
|
import { SystemRoleLiteral, UserRoleLiteral, AssistantRoleLiteral, ToolRoleLiteral, TextModalityLiteral, ImageModalityLiteral, ToolCallModalityLiteral, ToolResponseModalityLiteral, EmbeddingTextModalityLiteral, Config, Base64ImageContentTypeLiteral, Message, Tool, createTextContent, createToolCallContent, EmbeddingRequests, FloatEmbeddingLiteral, createPartialTextMessage, createPartialToolCallMessage } from '@adaline/types';
|
|
4
4
|
|
|
5
|
-
var
|
|
6
|
-
[${this.chatModelLiterals().join(", ")}]`)});let t=this.chatModelFactories[o].model,
|
|
7
|
-
[${this.embeddingModelLiterals().join(", ")}]`)});let t=this.embeddingModelFactories[o].model,s=this.embeddingModelFactories[o].modelOptions.parse(e);return new t(s)}};z.baseUrl="https://generativelanguage.googleapis.com/v1beta";var y=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),Nt="model",vt="function",C={system:UserRoleLiteral,user:UserRoleLiteral,assistant:Nt,tool:vt};var b=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],_=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),Tn=[TextModalityLiteral],Mn=z$1.enum([TextModalityLiteral]),Pe=[TextModalityLiteral,ImageModalityLiteral],Se=z$1.enum([TextModalityLiteral,ImageModalityLiteral]),v=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],F=z$1.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var Ft=z$1.object({text:z$1.string()}),$t=z$1.object({functionCall:z$1.object({name:z$1.string(),args:z$1.record(z$1.any())})}),et=z$1.object({candidates:z$1.array(z$1.object({content:z$1.object({role:z$1.string(),parts:z$1.array(z$1.union([Ft,$t]))}).optional(),finishReason:z$1.string(),index:z$1.number().optional(),safetyRatings:z$1.optional(z$1.array(z$1.object({category:z$1.string(),probability:z$1.string(),blocked:z$1.boolean().optional()})))})),promptFeedback:z$1.optional(z$1.object({safetyRatings:z$1.optional(z$1.array(z$1.object({category:z$1.string(),probability:z$1.string()})))})),usageMetadata:z$1.object({promptTokenCount:z$1.number(),cachedContentTokenCount:z$1.number().optional(),candidatesTokenCount:z$1.number().optional(),totalTokenCount:z$1.number()}).optional()}),qt=z$1.object({text:z$1.string()}),zt=z$1.object({functionCall:z$1.object({name:z$1.string(),args:z$1.record(z$1.any())})}),Go=z$1.object({candidates:z$1.array(z$1.object({content:z$1.object({role:z$1.string(),parts:z$1.array(z$1.union([qt,zt]))}).optional(),finishReason:z$1.string().optional(),index:z$1.number().optional(),safetyRatings:z$1.optional(z$1.array(z$1.object({category:z$1.string(),probability:z$1.string(),blocked:z$1.boolean().optional()})))})),promptFeedback:z$1.optional(z$1.object({safetyRatings:z$1.optional(z$1.array(z$1.object({category:z$1.string(),probability:z$1.string()})))})),usageMetadata:z$1.object({promptTokenCount:z$1.number().optional(),cachedContentTokenCount:z$1.number().optional(),candidatesTokenCount:z$1.number().optional(),totalTokenCount:z$1.number().optional()}).optional()});var it=z$1.object({text:z$1.string().min(1)}),Bt=z$1.object({inline_data:z$1.object({mime_type:z$1.string().min(1),data:z$1.string().base64()})}),jt=z$1.object({function_call:z$1.object({name:z$1.string().min(1),args:z$1.record(z$1.string().min(1))})}),Dt=z$1.object({function_response:z$1.object({name:z$1.string().min(1),response:z$1.record(z$1.string().min(1))})}),Ut=z$1.object({role:z$1.enum(["user","model","function"]),parts:z$1.array(z$1.union([it,Bt,jt,Dt]))}),ot=z$1.object({parts:z$1.array(it)}),At=z$1.object({name:z$1.string().min(1),description:z$1.string().min(1),parameters:z$1.any()}),tt=z$1.object({function_calling_config:z$1.object({mode:z$1.enum(["ANY","AUTO","NONE"]),allowed_function_names:z$1.array(z$1.string()).optional()})}),st=z$1.object({stopSequences:z$1.array(z$1.string()).optional(),maxOutputTokens:z$1.number().optional(),temperature:z$1.number().optional(),topP:z$1.number().optional(),topK:z$1.number().optional(),presencePenalty:z$1.number().optional(),frequencyPenalty:z$1.number().optional(),seed:z$1.number().optional()}),nt=z$1.object({category:z$1.enum(["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:z$1.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])}),at=z$1.object({model:z$1.string().min(1).optional(),contents:z$1.array(Ut),systemInstruction:ot.optional(),system_instruction:ot.optional(),generationConfig:st.optional(),generation_config:st.optional(),safetySettings:z$1.array(nt).optional(),safety_settings:z$1.array(nt).optional(),tools:z$1.object({function_declarations:z$1.array(At)}).optional(),toolConfig:tt.optional(),tool_config:tt.optional()});var f=z$1.object({modelName:z$1.string(),apiKey:z$1.string(),baseUrl:z$1.string().url().optional(),completeChatUrl:z$1.string().url().optional(),streamChatUrl:z$1.string().url().optional()}),T=class{constructor(e,o){this.version="v1";var s;let t=f.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash((s=t.baseUrl)!=null?s:z.baseUrl),this.completeChatUrl=urlWithoutTrailingSlash(t.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=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){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.reduce((o,t)=>o+t.content.map(s=>s.modality==="text"?s.value:"").join(" ").length,0)}transformModelRequest(e){let o=at.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,s=t.model;if(t.system_instruction&&t.systemInstruction)throw new 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 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 InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let n=t.system_instruction||t.systemInstruction,l=t.generation_config||t.generationConfig,r=t.safety_settings||t.safetySettings,m=t.tool_config||t.toolConfig;if(m&&(!t.tools||t.tools.function_declarations.length===0))throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let a={};m&&(m.function_calling_config.mode==="ANY"&&m.function_calling_config.allowed_function_names&&m.function_calling_config.allowed_function_names.length===1?a.toolChoice=m.function_calling_config.allowed_function_names[0]:a.toolChoice=m.function_calling_config.mode.toLowerCase()),a.seed=l==null?void 0:l.seed,a.maxTokens=l==null?void 0:l.maxOutputTokens,a.temperature=l==null?void 0:l.temperature,a.topP=l==null?void 0:l.topP,a.presencePenalty=l==null?void 0:l.presencePenalty,a.frequencyPenalty=l==null?void 0:l.frequencyPenalty,a.stop=l==null?void 0:l.stopSequences,a.safetySettings=r;let c=Config().parse(removeUndefinedEntries(a)),u=[];n&&n.parts.forEach(g=>{u.push({role:SystemRoleLiteral,content:[{modality:TextModalityLiteral,value:g.text}]});}),t.contents.forEach(g=>{let w=g.role;switch(w){case"user":{let k=g.parts.map(G=>"text"in G?{modality:TextModalityLiteral,value:G.text}:{modality:ImageModalityLiteral,detail:"auto",value:{type:Base64ImageContentTypeLiteral,base64:G.inline_data.data,media_type:G.inline_data.mime_type.split("/")[1]}});u.push({role:w,content:k});}break;case"model":{let k=g.parts.map((G,L)=>"text"in G?{modality:TextModalityLiteral,value:G.text}:{modality:ToolCallModalityLiteral,id:L.toString(),index:L,name:G.function_call.name,arguments:JSON.stringify(G.function_call.args)});u.push({role:AssistantRoleLiteral,content:k});}break;case"function":{let k=g.parts.map((G,L)=>({modality:ToolResponseModalityLiteral,id:L.toString(),index:L,name:G.function_response.name,data:JSON.stringify(G.function_response.response)}));u.push({role:ToolRoleLiteral,content:k});}break;default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${g.role}' is not supported for model : ${this.modelName}`)})}});let M=[];return t.tools&&t.tools.function_declarations.forEach(g=>{M.push({type:"function",definition:{schema:{name:g.name,description:g.description,parameters:g.parameters}}});}),{modelName:s,config:c,messages:u,tools:M.length>0?M:void 0}}transformConfig(e,o,t){let s=e.toolChoice;delete e.toolChoice;let n=this.modelSchema.config.schema.safeParse(e);if(!n.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:n.error});let l=n.data;Object.keys(l).forEach(c=>{if(!(c in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${c}',
|
|
8
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let r=Object.keys(
|
|
9
|
-
one of [${
|
|
5
|
+
var kt=Object.defineProperty;var No=Object.getOwnPropertySymbols;var wt=Object.prototype.hasOwnProperty,vt=Object.prototype.propertyIsEnumerable;var le=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s),Nt=s=>{throw TypeError(s)};var Io=(s,e,o)=>e in s?kt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):s[e]=o,E=(s,e)=>{for(var o in e||(e={}))wt.call(e,o)&&Io(s,o,e[o]);if(No)for(var o of No(e))vt.call(e,o)&&Io(s,o,e[o]);return s};var S=(s,e,o)=>new Promise((t,n)=>{var i=m=>{try{r(o.next(m));}catch(l){n(l);}},a=m=>{try{r(o.throw(m));}catch(l){n(l);}},r=m=>m.done?t(m.value):Promise.resolve(m.value).then(i,a);r((o=o.apply(s,e)).next());}),Lo=function(s,e){this[0]=s,this[1]=e;},no=(s,e,o)=>{var t=(a,r,m,l)=>{try{var g=o[a](r),T=(r=g.value)instanceof Lo,P=g.done;Promise.resolve(T?r[0]:r).then(C=>T?t(a==="return"?a:"next",r[1]?{done:C.done,value:C.value}:C,m,l):m({value:C,done:P})).catch(C=>t("throw",C,m,l));}catch(C){l(C);}},n=a=>i[a]=r=>new Promise((m,l)=>t(a,r,m,l)),i={};return o=o.apply(s,e),i[le("asyncIterator")]=()=>i,n("next"),n("throw"),n("return"),i},Do=s=>{var e=s[le("asyncIterator")],o=!1,t,n={};return e==null?(e=s[le("iterator")](),t=i=>n[i]=a=>e[i](a)):(e=e.call(s),t=i=>n[i]=a=>{if(o){if(o=!1,i==="throw")throw a;return a}return o=!0,{done:!1,value:new Lo(new Promise(r=>{var m=e[i](a);m instanceof Object||Nt("Object expected"),r(m);}),1)}}),n[le("iterator")]=()=>n,t("next"),"throw"in e?t("throw"):n.throw=i=>{throw i},"return"in e&&t("return"),n};var I=(s,e)=>RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:0,max:s,step:.01,default:e}),L=s=>RangeConfigItem({param:"maxOutputTokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:s,step:1,default:0}),D=s=>MultiStringConfigItem({param:"stopSequences",title:CHAT_CONFIG.STOP(s).title,description:CHAT_CONFIG.STOP(s).description,max:s}),F=s=>RangeConfigItem({param:"topP",title:CHAT_CONFIG.TOP_P.title,description:CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:s}),Y=s=>RangeConfigItem({param:"topK",title:CHAT_CONFIG.TOP_K.title,description:CHAT_CONFIG.TOP_K.description,min:1,max:40,step:1,default:s}),J=RangeConfigItem({param:"frequencyPenalty",title:CHAT_CONFIG.FREQUENCY_PENALTY.title,description:CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),W=RangeConfigItem({param:"presencePenalty",title:CHAT_CONFIG.PRESENCE_PENALTY.title,description:CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),X=RangeConfigItem({param:"seed",title:CHAT_CONFIG.SEED.title,description:CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),U=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"]}),$=ObjectSchemaConfigItem({param:"safetySettings",title:"Safety settings",description:"The safety rating contains the category of harm and the harm probability level in that category for a piece of content.",objectSchema:z.array(z.object({threshold:z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]),category:z.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"])}))}),io=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});var Fo=(s,e,o,t,n)=>z.object({temperature:I(s,e).schema,maxTokens:L(o).schema,stop:D(t).schema,topP:F(n).schema,toolChoice:U.schema,safetySettings:$.schema}),Uo=(s,e,o,t,n)=>({temperature:I(s,e).def,maxTokens:L(o).def,stop:D(t).def,topP:F(n).def,toolChoice:U.def,safetySettings:$.def});var $o=(s,e,o,t,n,i)=>z.object({temperature:I(s,e).schema,maxTokens:L(o).schema,stop:D(t).schema,topP:F(n).schema,topK:Y(i).schema,frequencyPenalty:J.schema,presencePenalty:W.schema,seed:X.schema.transform(a=>a===0?void 0:a),toolChoice:U.schema,safetySettings:$.schema}),qo=(s,e,o,t,n,i)=>({temperature:I(s,e).def,maxTokens:L(o).def,stop:D(t).def,topP:F(n).def,topK:Y(i).def,frequencyPenalty:J.def,presencePenalty:W.def,seed:X.def,toolChoice:U.def,safetySettings:$.def});var zo=(s,e,o,t,n,i)=>z.object({temperature:I(s,e).schema,maxTokens:L(o).schema,stop:D(t).schema,topP:F(n).schema,topK:Y(i).schema,frequencyPenalty:J.schema,presencePenalty:W.schema,seed:X.schema.transform(a=>a===0?void 0:a),toolChoice:U.schema,safetySettings:$.schema,reasoningEnabled:io.schema}),Bo=(s,e,o,t,n,i)=>({temperature:I(s,e).def,maxTokens:L(o).def,stop:D(t).def,topP:F(n).def,topK:Y(i).def,frequencyPenalty:J.def,presencePenalty:W.def,seed:X.def,toolChoice:U.def,safetySettings:$.def,reasoningEnabled:io.def});var so=s=>RangeConfigItem({param:"outputDimensionality",title:EMBEDDING_CONFIG.DIMENSIONS.title,description:EMBEDDING_CONFIG.DIMENSIONS.description,min:1,max:s,step:1,default:s});var Ao=s=>z.object({dimensions:so(s).schema}),Ho=s=>({dimensions:so(s).def});var p={base:(s,e,o,t,n)=>({def:Uo(s,e,o,t,n),schema:Fo(s,e,o,t,n)}),c1:(s,e,o,t,n,i)=>({def:qo(s,e,o,t,n,i),schema:$o(s,e,o,t,n,i)}),reasoning:(s,e,o,t,n,i)=>({def:Bo(s,e,o,t,n,i),schema:zo(s,e,o,t,n,i)})},Z={base:s=>({def:Ho(s),schema:Ao(s)})};var jt="google",K=class{constructor(){this.version="v1";this.name=jt;this.chatModelFactories={[Be]:{model:je,modelOptions:mt,modelSchema:Po},[qe]:{model:ze,modelOptions:lt,modelSchema:bo},[Ce]:{model:Te,modelOptions:Xo,modelSchema:po},[Me]:{model:Ge,modelOptions:Zo,modelSchema:co},[be]:{model:Pe,modelOptions:Qo,modelSchema:go},[_e]:{model:Ee,modelOptions:et,modelSchema:ho},[Oe]:{model:Se,modelOptions:ot,modelSchema:fo},[xe]:{model:Re,modelOptions:tt,modelSchema:uo},[ke]:{model:we,modelOptions:nt,modelSchema:yo},[ve]:{model:Ne,modelOptions:it,modelSchema:Co},[ue]:{model:ye,modelOptions:Wo,modelSchema:mo},[he]:{model:fe,modelOptions:Jo,modelSchema:lo},[ce]:{model:ge,modelOptions:Yo,modelSchema:ro},[de]:{model:pe,modelOptions:Ko,modelSchema:ao},[Ie]:{model:Le,modelOptions:st,modelSchema:To},[De]:{model:Fe,modelOptions:at,modelSchema:Mo},[Ue]:{model:$e,modelOptions:rt,modelSchema:Go}};this.embeddingModelFactories={[_o]:{model:Ae,modelOptions:dt,modelSchema:Eo},[Oo]:{model:He,modelOptions:pt,modelSchema:So}};}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 ProviderError({info:`Google chat model: ${o} not found`,cause:new Error(`Google chat model: ${o} not found, available chat models:
|
|
6
|
+
[${this.chatModelLiterals().join(", ")}]`)});let t=this.chatModelFactories[o].model,n=this.chatModelFactories[o].modelOptions.parse(e);return new t(n)}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 ProviderError({info:`Google embedding model: ${o} not found`,cause:new Error(`Google embedding model: ${o} not found, available embedding models:
|
|
7
|
+
[${this.embeddingModelLiterals().join(", ")}]`)});let t=this.embeddingModelFactories[o].model,n=this.embeddingModelFactories[o].modelOptions.parse(e);return new t(n)}};K.baseUrl="https://generativelanguage.googleapis.com/v1beta";var h={"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}}}]}};var u=z.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),Jt="model",Wt="function",y={system:UserRoleLiteral,user:UserRoleLiteral,assistant:Jt,tool:Wt};var G=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],b=z.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),Bi=[TextModalityLiteral],ji=z.enum([TextModalityLiteral]),We=[TextModalityLiteral,ImageModalityLiteral],Xe=z.enum([TextModalityLiteral,ImageModalityLiteral]),B=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],j=z.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var Xt=z.object({text:z.string()}),Zt=z.object({functionCall:z.object({name:z.string(),args:z.record(z.any())})}),ct=z.object({candidates:z.array(z.object({content:z.object({role:z.string(),parts:z.array(z.union([Xt,Zt]))}).optional(),finishReason:z.string(),index:z.number().optional(),safetyRatings:z.optional(z.array(z.object({category:z.string(),probability:z.string(),blocked:z.boolean().optional()})))})),promptFeedback:z.optional(z.object({safetyRatings:z.optional(z.array(z.object({category:z.string(),probability:z.string()})))})),usageMetadata:z.object({promptTokenCount:z.number(),cachedContentTokenCount:z.number().optional(),candidatesTokenCount:z.number().optional(),totalTokenCount:z.number()}).optional()}),Qt=z.object({text:z.string()}),en=z.object({functionCall:z.object({name:z.string(),args:z.record(z.any())})}),Ro=z.object({candidates:z.array(z.object({content:z.object({role:z.string(),parts:z.array(z.union([Qt,en]))}).optional(),finishReason:z.string().optional(),index:z.number().optional(),safetyRatings:z.optional(z.array(z.object({category:z.string(),probability:z.string(),blocked:z.boolean().optional()})))})),promptFeedback:z.optional(z.object({safetyRatings:z.optional(z.array(z.object({category:z.string(),probability:z.string()})))})),usageMetadata:z.object({promptTokenCount:z.number().optional(),cachedContentTokenCount:z.number().optional(),candidatesTokenCount:z.number().optional(),totalTokenCount:z.number().optional()}).optional()});var yt=z.object({text:z.string().min(1)}),on=z.object({inline_data:z.object({mime_type:z.string().min(1),data:z.string().base64()})}),tn=z.object({function_call:z.object({name:z.string().min(1),args:z.record(z.string().min(1))})}),nn=z.object({function_response:z.object({name:z.string().min(1),response:z.record(z.string().min(1))})}),sn=z.object({role:z.enum(["user","model","function"]),parts:z.array(z.union([yt,on,tn,nn]))}),gt=z.object({parts:z.array(yt)}),an=z.object({name:z.string().min(1),description:z.string().min(1),parameters:z.any()}),ht=z.object({function_calling_config:z.object({mode:z.enum(["ANY","AUTO","NONE"]),allowed_function_names:z.array(z.string()).optional()})}),ft=z.object({stopSequences:z.array(z.string()).optional(),maxOutputTokens:z.number().optional(),temperature:z.number().optional(),topP:z.number().optional(),topK:z.number().optional(),presencePenalty:z.number().optional(),frequencyPenalty:z.number().optional(),seed:z.number().optional()}),ut=z.object({category:z.enum(["HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])}),Ct=z.object({model:z.string().min(1).optional(),contents:z.array(sn),systemInstruction:gt.optional(),system_instruction:gt.optional(),generationConfig:ft.optional(),generation_config:ft.optional(),safetySettings:z.array(ut).optional(),safety_settings:z.array(ut).optional(),tools:z.object({function_declarations:z.array(an)}).optional(),toolConfig:ht.optional(),tool_config:ht.optional()});var f=z.object({modelName:z.string(),apiKey:z.string(),baseUrl:z.string().url().optional(),completeChatUrl:z.string().url().optional(),streamChatUrl:z.string().url().optional()}),M=class{constructor(e,o){this.version="v1";var n;let t=f.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash((n=t.baseUrl)!=null?n:K.baseUrl),this.completeChatUrl=urlWithoutTrailingSlash(t.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=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){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.reduce((o,t)=>o+t.content.map(n=>n.modality==="text"?n.value:"").join(" ").length,0)}transformModelRequest(e){let o=Ct.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,n=t.model;if(t.system_instruction&&t.systemInstruction)throw new 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 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 InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tool_config' and 'toolConfig' are not allowed at the same time")});let i=t.system_instruction||t.systemInstruction,a=t.generation_config||t.generationConfig,r=t.safety_settings||t.safetySettings,m=t.tool_config||t.toolConfig;if(m&&(!t.tools||t.tools.function_declarations.length===0))throw new InvalidModelRequestError({info:`Invalid model request for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'tool_choice' is specified")});let l={};m&&(m.function_calling_config.mode==="ANY"&&m.function_calling_config.allowed_function_names&&m.function_calling_config.allowed_function_names.length===1?l.toolChoice=m.function_calling_config.allowed_function_names[0]:l.toolChoice=m.function_calling_config.mode.toLowerCase()),l.seed=a==null?void 0:a.seed,l.maxTokens=a==null?void 0:a.maxOutputTokens,l.temperature=a==null?void 0:a.temperature,l.topP=a==null?void 0:a.topP,l.presencePenalty=a==null?void 0:a.presencePenalty,l.frequencyPenalty=a==null?void 0:a.frequencyPenalty,l.stop=a==null?void 0:a.stopSequences,l.safetySettings=r;let g=Config().parse(removeUndefinedEntries(l)),T=[];i&&i.parts.forEach(C=>{T.push({role:SystemRoleLiteral,content:[{modality:TextModalityLiteral,value:C.text}]});}),t.contents.forEach(C=>{let w=C.role;switch(w){case"user":{let v=C.parts.map(_=>"text"in _?{modality:TextModalityLiteral,value:_.text}:{modality:ImageModalityLiteral,detail:"auto",value:{type:Base64ImageContentTypeLiteral,base64:_.inline_data.data,media_type:_.inline_data.mime_type.split("/")[1]}});T.push({role:w,content:v});}break;case"model":{let v=C.parts.map((_,q)=>"text"in _?{modality:TextModalityLiteral,value:_.text}:{modality:ToolCallModalityLiteral,id:q.toString(),index:q,name:_.function_call.name,arguments:JSON.stringify(_.function_call.args)});T.push({role:AssistantRoleLiteral,content:v});}break;case"function":{let v=C.parts.map((_,q)=>({modality:ToolResponseModalityLiteral,id:q.toString(),index:q,name:_.function_response.name,data:JSON.stringify(_.function_response.response)}));T.push({role:ToolRoleLiteral,content:v});}break;default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${C.role}' is not supported for model : ${this.modelName}`)})}});let P=[];return t.tools&&t.tools.function_declarations.forEach(C=>{P.push({type:"function",definition:{schema:{name:C.name,description:C.description,parameters:C.parameters}}});}),{modelName:n,config:g,messages:T,tools:P.length>0?P:void 0}}transformConfig(e,o,t){let n=e.toolChoice;delete e.toolChoice;let i=this.modelSchema.config.schema.safeParse(e);if(!i.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:i.error});let a=i.data;Object.keys(a).forEach(g=>{if(!(g in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${g}',
|
|
8
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let r=Object.keys(a).reduce((g,T)=>{let P=this.modelSchema.config.def[T],C=P.param,w=a[T];return T==="reasoningEnabled"?g.thinkingConfig={includeThoughts:w}:C==="maxOutputTokens"&&P.type==="range"&&w===0?g[C]=P.max:g[C]=w,g},{}),m=r.safetySettings;delete r.safetySettings;let l;if(n!==void 0){let g=n;if(!t||t&&t.length===0)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(t&&t.length>0){let T=this.modelSchema.config.def.toolChoice;if(T.choices.includes(g))g==="any"?l={function_calling_config:{mode:"ANY",allowed_function_names:t.map(P=>P.definition.schema.name)}}:l={function_calling_config:{mode:g.toUpperCase()}};else if(t.map(P=>P.definition.schema.name).includes(g))l={function_calling_config:{mode:"ANY",allowed_function_names:[g]}};else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${g}' is not part of provided 'tools' names or
|
|
9
|
+
one of [${T.choices.join(", ")}]`)})}}return E(E({generation_config:r},l?{tool_config:l}:{}),m?{safety_settings:m}:{})}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let o=r=>{let m=r.match(/^data:image\/[a-zA-Z]+;base64,/);return m?r.substring(m[0].length):r},t=e.map(r=>{let m=Message().safeParse(r);if(!m.success)throw new InvalidMessagesError({info:"Invalid messages",cause:m.error});return m.data});t.forEach(r=>{r.content.forEach(m=>{if(!this.modelSchema.modalities.includes(m.modality))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${m.modality}',
|
|
10
10
|
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(r=>{if(!Object.keys(this.modelSchema.roles).includes(r.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${r.role}',
|
|
11
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let
|
|
12
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),
|
|
13
|
-
`,a);if(c===-1){m=l.substring(a);break}else {let u=l.substring(a,c).trim();u&&r.push(u),a=c+1;}}for(let c of r){if(c==="data: [DONE]")return;if(c.startsWith("data: ")){let u=c.substring(6);try{let M=JSON.parse(u),g=Go.safeParse(M);if(g.success){let w={partialMessages:[]},x=g.data;if(x.candidates.length>0){let k=x.candidates[0].content;k&&"parts"in k&&k.parts.length>0&&k.parts.forEach((G,L)=>{if("text"in G&&G.text!==void 0&&w.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,G.text)),"functionCall"in G&&G.functionCall!==void 0){let Ie=G.functionCall;w.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,L,`${Ie.name}_${L}`,Ie.name,JSON.stringify(Ie.args)));}});}x.usageMetadata&&x.usageMetadata.totalTokenCount&&x.usageMetadata.promptTokenCount&&x.usageMetadata.candidatesTokenCount&&(w.usage={promptTokens:x.usageMetadata.promptTokenCount,completionTokens:x.usageMetadata.candidatesTokenCount,totalTokens:x.usageMetadata.totalTokenCount}),yield {partialResponse:w,buffer:o};}else throw new ModelResponseError({info:"Invalid response from model",cause:g.error})}catch(M){throw new ModelResponseError({info:`Malformed JSON received in stream: ${u}`,cause:M})}}}yield {partialResponse:{partialMessages:[]},buffer:m};})}getProxyCompleteChatUrl(e,o,t){return P(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getProxyStreamChatUrl(e,o,t){return P(this,null,function*(){return new Promise(s=>{if(!t||Object.keys(t).length===0){s(this.streamChatUrl);return}let n=new URL(this.streamChatUrl);Object.entries(t).forEach(([l,r])=>{r!=null&&n.searchParams.set(l,r);}),s(n.toString());})})}getProxyCompleteChatHeaders(e,o,t){return P(this,null,function*(){if(!o)return {};let s=E({},o);return delete s.host,delete s["content-length"],s})}getProxyStreamChatHeaders(e,o,t){return P(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,o,t)})}};var R=class extends T{transformMessages(e){let o=super.transformMessages(e);if(o.systemInstruction){let t={role:this.modelSchema.roles[UserRoleLiteral],parts:o.systemInstruction.parts};o.contents.unshift(t),delete o.systemInstruction;}return o}};var ze="gemini-1.0-pro-001",es="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Be=ChatModelSchema(y,F).parse({name:ze,description:es,maxInputTokens:30720,maxOutputTokens:2048,roles:C,modalities:v,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),$o=f,ie=class extends R{constructor(e){super(Be,e);}};var je="gemini-1.0-pro-latest",ts="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for natural language tasks, multi-turn text and code chat, and code generation",De=ChatModelSchema(y,F).parse({name:je,description:ts,maxInputTokens:30720,maxOutputTokens:2048,roles:C,modalities:v,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),qo=f,ae=class extends R{constructor(e){super(De,e);}};var Ue="gemini-1.0-pro-vision",ns="Google's predecessor to Gemini 1.5 Pro, an image understanding model to handle a broad range of applications",Ae=ChatModelSchema(y,Se).parse({name:Ue,description:ns,maxInputTokens:12288,maxOutputTokens:4096,roles:C,modalities:Pe,config:{def:h.c1(1,.4,4096,4,1,32).def,schema:h.c1(1,.4,4096,4,1,32).schema}}),zo=f,re=class extends R{constructor(e){super(Ae,e);}};var He="gemini-1.0-pro",as="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Ve=ChatModelSchema(y,F).parse({name:He,description:as,maxInputTokens:30720,maxOutputTokens:2048,roles:C,modalities:v,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),Bo=f,le=class extends R{constructor(e){super(Ve,e);}};var Ke="gemini-1.5-flash-001",ls="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",Ye=ChatModelSchema(y,_).parse({name:Ke,description:ls,maxInputTokens:1e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),jo=f,me=class extends T{constructor(e){super(Ye,e);}};var Je="gemini-1.5-flash-002",ds="Google's fastest, most cost-efficient multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",We=ChatModelSchema(y,_).parse({name:Je,description:ds,maxInputTokens:1e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,40).def,schema:h.c1(2,1,8192,4,.95,40).schema}}),Do=f,de=class extends T{constructor(e){super(We,e);}};var Xe="gemini-1.5-flash-latest",cs="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Ze=ChatModelSchema(y,_).parse({name:Xe,description:cs,maxInputTokens:1e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Uo=f,pe=class extends T{constructor(e){super(Ze,e);}};var Qe="gemini-1.5-flash",gs="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",eo=ChatModelSchema(y,_).parse({name:Qe,description:gs,maxInputTokens:1e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Ao=f,ce=class extends T{constructor(e){super(eo,e);}};var oo="gemini-1.5-pro-001",us="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",to=ChatModelSchema(y,_).parse({name:oo,description:us,maxInputTokens:2e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Ho=f,he=class extends T{constructor(e){super(to,e);}};var so="gemini-1.5-pro-002",Cs="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",no=ChatModelSchema(y,_).parse({name:so,description:Cs,maxInputTokens:2e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,40).def,schema:h.c1(2,1,8192,4,.95,40).schema}}),Vo=f,ge=class extends T{constructor(e){super(no,e);}};var io="gemini-1.5-pro-latest",Ms="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",ao=ChatModelSchema(y,_).parse({name:io,description:Ms,maxInputTokens:2e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Ko=f,fe=class extends T{constructor(e){super(ao,e);}};var ro="gemini-1.5-pro",bs="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",lo=ChatModelSchema(y,_).parse({name:ro,description:bs,maxInputTokens:2e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Yo=f,ue=class extends T{constructor(e){super(lo,e);}};var mo="gemini-2.0-flash-exp",Es="Google's experimental multimodal model with enhanced capabilities. Designed for cutting-edge performance across complex and high-frequency tasks.",po=ChatModelSchema(y,_).parse({name:mo,description:Es,maxInputTokens:1e6,maxOutputTokens:8192,roles:C,modalities:b,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Jo=f,ye=class extends T{constructor(e){super(po,e);}};var co="gemini-pro-vision",Ps="An image understanding model to handle a broad range of applications",ho=ChatModelSchema(y,Se).parse({name:co,description:Ps,maxInputTokens:12288,maxOutputTokens:4096,roles:C,modalities:Pe,config:{def:h.c1(1,.4,4096,4,1,32).def,schema:h.c1(1,.4,4096,4,1,32).schema}}),Wo=f,Ce=class extends R{constructor(e){super(ho,e);}};var go="gemini-pro",Rs="A model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",fo=ChatModelSchema(y,F).parse({name:go,description:Rs,maxInputTokens:30720,maxOutputTokens:2048,roles:C,modalities:v,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),Xo=f,Te=class extends R{constructor(e){super(fo,e);}};var we=[EmbeddingTextModalityLiteral],ke=z$1.enum([EmbeddingTextModalityLiteral]);var gt=z$1.object({embeddings:z$1.array(z$1.object({values:z$1.array(z$1.number())}))});var ws=z$1.object({model:z$1.string().min(1),content:z$1.object({parts:z$1.array(z$1.object({text:z$1.string().min(1)})).min(1)})}),ft=z$1.object({model:z$1.string().min(1).optional(),requests:z$1.array(ws).min(1),outputDimensionality:z$1.number().int().min(1).optional()});var te=z$1.object({modelName:z$1.string(),apiKey:z$1.string(),baseUrl:z$1.string().url().optional(),getEmbeddingsUrl:z$1.string().url().optional()}),W=class{constructor(e,o){this.version="v1";let t=te.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash(t.baseUrl||z.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(t.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((o,t)=>o+t.length,0)}transformModelRequest(e){let o=ft.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,s=t.model,n={outputDimensionality:t.outputDimensionality},l=Config().parse(removeUndefinedEntries(n)),r={modality:EmbeddingTextModalityLiteral,requests:t.requests.reduce((m,a)=>(m.push(...a.content.parts.map(c=>c.text)),m),[])};return {modelName:s,config:l,embeddingRequests:r}}transformConfig(e,o){let t=this.modelSchema.config.schema.safeParse(e);if(!t.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:t.error});let s=t.data;return Object.keys(s).forEach(l=>{if(!this.modelSchema.config.def[l])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${l}',
|
|
14
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(
|
|
11
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let n={parts:[]},i=[];if(t.forEach(r=>{switch(r.role){case SystemRoleLiteral:r.content.forEach(m=>{if(m.modality===TextModalityLiteral)n.parts.push({text:m.value});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${m.modality}'`)})});break;case AssistantRoleLiteral:{let m=[];r.content.forEach(l=>{if(l.modality===TextModalityLiteral)m.push({text:l.value});else if(l.modality===ToolCallModalityLiteral)m.push({function_call:{name:l.name,args:JSON.parse(l.arguments)}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:m});}break;case UserRoleLiteral:{let m=[];r.content.forEach(l=>{if(l.modality===TextModalityLiteral)m.push({text:l.value});else if(l.modality===ImageModalityLiteral){if(l.value.type==="base64"){let g=l.value.base64;g=o(g),m.push({inline_data:{mime_type:`image/${l.value.media_type}`,data:g}});}else if(l.value.type==="url")throw new InvalidMessagesError({info:`Invalid message 'modality' for model : ${this.modelName}`,cause:new Error(`model: '${this.modelName}' does not support image content type: '${l.value.type}'`)})}else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:m});}break;case ToolRoleLiteral:{let m=[];r.content.forEach(l=>{if(l.modality===ToolResponseModalityLiteral)m.push({function_response:{name:l.name,response:JSON.parse(l.data)}});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' cannot have content with modality : '${l.modality}'`)})}),i.push({role:this.modelSchema.roles[r.role],parts:m});}break;default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${r.role}' is not supported,
|
|
12
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),i[0].role!==this.modelSchema.roles[UserRoleLiteral])throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' requires first message to be from user`)});let a=r=>r===this.modelSchema.roles[UserRoleLiteral]||r===this.modelSchema.roles[ToolRoleLiteral]?[this.modelSchema.roles[AssistantRoleLiteral]]:[this.modelSchema.roles[UserRoleLiteral],this.modelSchema.roles[ToolRoleLiteral]];for(let r=1;r<i.length;r++)if(!a(i[r-1].role).includes(i[r].role))throw new InvalidMessagesError({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${i[r].role}' after message with role : '${i[r-1].role}'`)});if(i[i.length-1].role!==this.modelSchema.roles[UserRoleLiteral]&&i[i.length-1].role!==this.modelSchema.roles[ToolRoleLiteral])throw new 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:i},n.parts.length>0?{system_instruction:n}:{})}transformTools(e){if(!this.modelSchema.modalities.includes(ToolCallModalityLiteral))throw new InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' does not support tool modality : '${ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:[{function_declarations:e.map(n=>{let i=Tool().safeParse(n);if(!i.success)throw new InvalidToolsError({info:"Invalid tools",cause:i.error});return i.data}).map(n=>({name:n.definition.schema.name,description:n.definition.schema.description,parameters:n.definition.schema.parameters}))}]}}getCompleteChatUrl(e,o,t){return S(this,null,function*(){return new Promise(n=>{n(this.completeChatUrl);})})}getCompleteChatHeaders(e,o,t){return S(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getCompleteChatData(e,o,t){return S(this,null,function*(){let n=this.transformConfig(e,o,t),i=this.transformMessages(o);if(i.messages&&i.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let a=t?this.transformTools(t):{};return new Promise(r=>{r(E(E(E(E({},this.getDefaultParams()),n),i),a));})})}transformCompleteChatResponse(e){let o=ct.safeParse(e);if(o.success){if(o.data.candidates.length===0)throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(o.data)}`)});let t=o.data,n=[],i,a=t.candidates[0].content;if(a){let l=a.parts.map((g,T)=>{if("text"in g&&g.text!==void 0)return createTextContent(g.text);if("functionCall"in g&&g.functionCall!==void 0)return createToolCallContent(T,`${g.functionCall.name}_${T}`,g.functionCall.name,JSON.stringify(g.functionCall.args))});return n.push({role:AssistantRoleLiteral,content:l}),t.usageMetadata&&(i={promptTokens:t.usageMetadata.promptTokenCount,totalTokens:t.usageMetadata.totalTokenCount,completionTokens:t.usageMetadata.candidatesTokenCount||0}),{messages:n,usage:i,logProbs:void 0}}let r=t.candidates[0].safetyRatings;if(r&&r.length>0&&r.forEach(l=>{if(l.blocked)throw new ModelResponseError({info:`Blocked content for category: ${l.category} with probability: ${l.probability}`,cause:new Error(`Blocked content for category: ${l.category} with probability: ${l.probability}`)})}),t.candidates[0].finishReason==="SAFETY")throw new ModelResponseError({info:"Blocked content, model response finished with safety reason",cause:new Error("Blocked content, model response finished with safety reason")})}throw new ModelResponseError({info:"Invalid response from model",cause:o.error})}getStreamChatUrl(e,o,t){return S(this,null,function*(){return new Promise(n=>{n(this.streamChatUrl);})})}getStreamChatHeaders(e,o,t){return S(this,null,function*(){return new Promise(n=>{n(this.getDefaultHeaders());})})}getStreamChatData(e,o,t){return S(this,null,function*(){let n=this.transformConfig(e,o,t),i=this.transformMessages(o);if(i.messages&&i.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let a=t?this.transformTools(t):{};return new Promise(r=>{r(E(E(E(E({},this.getDefaultParams()),n),i),a));})})}transformStreamChatResponseChunk(e,o){return no(this,null,function*(){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 a;try{a=JSON.parse(i);}catch(m){if(m instanceof SyntaxError){o=i;continue}else throw m}o="";let r=Ro.safeParse(a);if(r.success){let m={partialMessages:[]},l=r.data;if(l.candidates.length>0){let g=l.candidates[0].content;g&&"parts"in g&&g.parts.length>0&&g.parts.forEach((T,P)=>{if("text"in T&&T.text!==void 0&&m.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,T.text)),"functionCall"in T&&T.functionCall!==void 0){let C=T.functionCall;m.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,P,`${C.name}_${P}`,C.name,JSON.stringify(C.args)));}});}l.usageMetadata&&(m.usage={promptTokens:l.usageMetadata.promptTokenCount,completionTokens:l.usageMetadata.candidatesTokenCount,totalTokens:l.usageMetadata.totalTokenCount}),yield {partialResponse:m,buffer:o};}else throw new ModelResponseError({info:"Invalid response from model",cause:r.error})}yield {partialResponse:{partialMessages:[]},buffer:o};})}transformProxyStreamChatResponseChunk(e,o,t,n,i){return no(this,null,function*(){if((i==null?void 0:i.alt)!=="sse"){yield*Do(this.transformStreamChatResponseChunk(e,o));return}let a=o+e,r=[],m="",l=0;for(;l<a.length;){let g=a.indexOf(`
|
|
13
|
+
`,l);if(g===-1){m=a.substring(l);break}else {let T=a.substring(l,g).trim();T&&r.push(T),l=g+1;}}for(let g of r){if(g==="data: [DONE]")return;if(g.startsWith("data: ")){let T=g.substring(6);try{let P=JSON.parse(T),C=Ro.safeParse(P);if(C.success){let w={partialMessages:[]},k=C.data;if(k.candidates.length>0){let v=k.candidates[0].content;v&&"parts"in v&&v.parts.length>0&&v.parts.forEach((_,q)=>{if("text"in _&&_.text!==void 0&&w.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,_.text)),"functionCall"in _&&_.functionCall!==void 0){let to=_.functionCall;w.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,q,`${to.name}_${q}`,to.name,JSON.stringify(to.args)));}});}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}),yield {partialResponse:w,buffer:o};}else throw new ModelResponseError({info:"Invalid response from model",cause:C.error})}catch(P){throw new ModelResponseError({info:`Malformed JSON received in stream: ${T}`,cause:P})}}}yield {partialResponse:{partialMessages:[]},buffer:m};})}getProxyCompleteChatUrl(e,o,t){return S(this,null,function*(){return new Promise(n=>{n(this.completeChatUrl);})})}getProxyStreamChatUrl(e,o,t){return S(this,null,function*(){return new Promise(n=>{if(!t||Object.keys(t).length===0){n(this.streamChatUrl);return}let i=new URL(this.streamChatUrl);Object.entries(t).forEach(([a,r])=>{r!=null&&i.searchParams.set(a,r);}),n(i.toString());})})}getProxyCompleteChatHeaders(e,o,t){return S(this,null,function*(){if(!o)return {};let n=E({},o);return delete n.host,delete n["content-length"],n})}getProxyStreamChatHeaders(e,o,t){return S(this,null,function*(){return yield this.getProxyCompleteChatHeaders(e,o,t)})}getModelPricing(){if(!(this.modelName in h))throw new ModelResponseError({info:`Invalid model pricing for model : '${this.modelName}'`,cause:new Error(`No pricing configuration found for model "${this.modelName}"`)});return h[this.modelName]}};var R=class extends M{transformMessages(e){let o=super.transformMessages(e);if(o.systemInstruction){let t={role:this.modelSchema.roles[UserRoleLiteral],parts:o.systemInstruction.parts};o.contents.unshift(t),delete o.systemInstruction;}return o}};var de="gemini-1.0-pro-001",un="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",ao=ChatModelSchema(u,j).parse({name:de,description:un,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:B,config:{def:p.base(1,.9,2048,4,1).def,schema:p.base(1,.9,2048,4,1).schema},price:h[de]}),Ko=f,pe=class extends R{constructor(e){super(ao,e);}};var ce="gemini-1.0-pro-latest",Cn="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for natural language tasks, multi-turn text and code chat, and code generation",ro=ChatModelSchema(u,j).parse({name:ce,description:Cn,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:B,config:{def:p.base(1,.9,2048,4,1).def,schema:p.base(1,.9,2048,4,1).schema},price:h[ce]}),Yo=f,ge=class extends R{constructor(e){super(ro,e);}};var he="gemini-1.0-pro-vision",Mn="Google's predecessor to Gemini 1.5 Pro, an image understanding model to handle a broad range of applications",lo=ChatModelSchema(u,Xe).parse({name:he,description:Mn,maxInputTokens:12288,maxOutputTokens:4096,roles:y,modalities:We,config:{def:p.c1(1,.4,4096,4,1,32).def,schema:p.c1(1,.4,4096,4,1,32).schema},price:h[he]}),Jo=f,fe=class extends R{constructor(e){super(lo,e);}};var ue="gemini-1.0-pro",bn="Google's predecessor to Gemini 1.5 Pro, a model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",mo=ChatModelSchema(u,j).parse({name:ue,description:bn,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:B,config:{def:p.base(1,.9,2048,4,1).def,schema:p.base(1,.9,2048,4,1).schema},price:h[ue]}),Wo=f,ye=class extends R{constructor(e){super(mo,e);}};var Ce="gemini-1.5-flash-001",_n="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=ChatModelSchema(u,b).parse({name:Ce,description:_n,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[Ce]}),Xo=f,Te=class extends M{constructor(e){super(po,e);}};var Me="gemini-1.5-flash-002",On="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",co=ChatModelSchema(u,b).parse({name:Me,description:On,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,40).def,schema:p.c1(2,1,8192,4,.95,40).schema},price:h[Me]}),Zo=f,Ge=class extends M{constructor(e){super(co,e);}};var be="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",go=ChatModelSchema(u,b).parse({name:be,description:xn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[be]}),Qo=f,Pe=class extends M{constructor(e){super(go,e);}};var _e="gemini-1.5-flash",kn="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",ho=ChatModelSchema(u,b).parse({name:_e,description:kn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[_e]}),et=f,Ee=class extends M{constructor(e){super(ho,e);}};var Oe="gemini-1.5-pro-001",vn="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",fo=ChatModelSchema(u,b).parse({name:Oe,description:vn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[Oe]}),ot=f,Se=class extends M{constructor(e){super(fo,e);}};var xe="gemini-1.5-pro-002",In="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",uo=ChatModelSchema(u,b).parse({name:xe,description:In,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,40).def,schema:p.c1(2,1,8192,4,.95,40).schema},price:h[xe]}),tt=f,Re=class extends M{constructor(e){super(uo,e);}};var ke="gemini-1.5-pro-latest",Dn="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",yo=ChatModelSchema(u,b).parse({name:ke,description:Dn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[ke]}),nt=f,we=class extends M{constructor(e){super(yo,e);}};var ve="gemini-1.5-pro",Un="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Co=ChatModelSchema(u,b).parse({name:ve,description:Un,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[ve]}),it=f,Ne=class extends M{constructor(e){super(Co,e);}};var Ie="gemini-2.0-flash-exp",qn="Google's experimental multimodal model with enhanced capabilities. Designed for cutting-edge performance across complex and high-frequency tasks.",To=ChatModelSchema(u,b).parse({name:Ie,description:qn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.c1(2,1,8192,4,.95,64).def,schema:p.c1(2,1,8192,4,.95,64).schema},price:h[Ie]}),st=f,Le=class extends M{constructor(e){super(To,e);}};var De="gemini-2.5-flash-preview-04-17",Bn="Google's fast and cost-efficient multimodal model for adaptive thinking.",Mo=ChatModelSchema(u,b).parse({name:De,description:Bn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.reasoning(2,1,8192,4,.95,64).def,schema:p.reasoning(2,1,8192,4,.95,64).schema},price:h[De]}),at=f,Fe=class extends M{constructor(e){super(Mo,e);}};var Ue="gemini-2.5-pro-preview-03-25",An="Google's preview model for enhanced thinking, reasoning, multimodal understanding, and advanced coding.",Go=ChatModelSchema(u,b).parse({name:Ue,description:An,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:G,config:{def:p.reasoning(2,1,8192,4,.95,64).def,schema:p.reasoning(2,1,8192,4,.95,64).schema},price:h[Ue]}),rt=f,$e=class extends M{constructor(e){super(Go,e);}};var qe="gemini-pro-vision",Vn="An image understanding model to handle a broad range of applications",bo=ChatModelSchema(u,Xe).parse({name:qe,description:Vn,maxInputTokens:12288,maxOutputTokens:4096,roles:y,modalities:We,config:{def:p.c1(1,.4,4096,4,1,32).def,schema:p.c1(1,.4,4096,4,1,32).schema},price:h[qe]}),lt=f,ze=class extends R{constructor(e){super(bo,e);}};var Be="gemini-pro",Yn="A model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",Po=ChatModelSchema(u,j).parse({name:Be,description:Yn,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:B,config:{def:p.base(1,.9,2048,4,1).def,schema:p.base(1,.9,2048,4,1).schema},price:h[Be]}),mt=f,je=class extends R{constructor(e){super(Po,e);}};var eo=[EmbeddingTextModalityLiteral],oo=z.enum([EmbeddingTextModalityLiteral]);var Ot=z.object({embeddings:z.array(z.object({values:z.array(z.number())}))});var Wn=z.object({model:z.string().min(1),content:z.object({parts:z.array(z.object({text:z.string().min(1)})).min(1)})}),St=z.object({model:z.string().min(1).optional(),requests:z.array(Wn).min(1),outputDimensionality:z.number().int().min(1).optional()});var re=z.object({modelName:z.string(),apiKey:z.string(),baseUrl:z.string().url().optional(),getEmbeddingsUrl:z.string().url().optional()}),oe=class{constructor(e,o){this.version="v1";let t=re.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash(t.baseUrl||K.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(t.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((o,t)=>o+t.length,0)}transformModelRequest(e){let o=St.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,n=t.model,i={outputDimensionality:t.outputDimensionality},a=Config().parse(removeUndefinedEntries(i)),r={modality:EmbeddingTextModalityLiteral,requests:t.requests.reduce((m,l)=>(m.push(...l.content.parts.map(g=>g.text)),m),[])};return {modelName:n,config:a,embeddingRequests:r}}transformConfig(e,o){let t=this.modelSchema.config.schema.safeParse(e);if(!t.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:t.error});let n=t.data;return Object.keys(n).forEach(a=>{if(!this.modelSchema.config.def[a])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${a}',
|
|
14
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(n).reduce((a,r)=>{let l=this.modelSchema.config.def[r].param,g=n[r];return a[l]=g,a},{})}transformEmbeddingRequests(e){let o=EmbeddingRequests().safeParse(e);if(!o.success)throw new InvalidEmbeddingRequestsError({info:"Invalid embedding requests",cause:o.error});if(e.modality!==EmbeddingTextModalityLiteral)throw new InvalidEmbeddingRequestsError({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error(`Only '${EmbeddingTextModalityLiteral}' modality is supported for model : '${this.modelName}'`)});return {requests:o.data.requests.map(n=>({model:`models/${this.modelName}`,content:{parts:[{text:n}]}}))}}getGetEmbeddingsUrl(e,o){return S(this,null,function*(){return new Promise(t=>{t(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,o){return S(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,o){return S(this,null,function*(){return new Promise(t=>{let n=this.transformConfig(e),i=this.transformEmbeddingRequests(o);if(o.requests.length===0)throw new InvalidEmbeddingRequestsError({info:`Invalid embedding requests for model : '${this.modelName}'`,cause:new Error("requests cannot be empty")});n.outputDimensionality&&(i.requests.forEach(a=>{a.outputDimensionality=n.outputDimensionality;}),delete n.outputDimensionality),t(E(E(E({},this.getDefaultParams()),n),i));})})}transformGetEmbeddingsResponse(e){let o=Ot.safeParse(e);if(o.success){let n=o.data.embeddings.map((i,a)=>({index:a,embedding:i.values}));return {encodingFormat:FloatEmbeddingLiteral,embeddings:n}}throw new ModelResponseError({info:"Invalid response from model",cause:o.error})}};var _o="text-embedding-001",ii="text-embedding-001",Eo=EmbeddingModelSchema(oo).parse({name:_o,description:ii,modalities:eo,maxInputTokens:2048,maxOutputTokens:768,config:{def:Z.base(768).def,schema:Z.base(768).schema}}),dt=re,Ae=class extends oe{constructor(e){super(Eo,e);}};var Oo="text-embedding-004",ai="text-embedding-004",So=EmbeddingModelSchema(oo).parse({name:Oo,description:ai,modalities:eo,maxInputTokens:2048,maxOutputTokens:768,config:{def:Z.base(768).def,schema:Z.base(768).schema}}),pt=re,He=class extends oe{constructor(e){super(So,e);}};
|
|
15
15
|
|
|
16
|
-
export {
|
|
16
|
+
export { M as BaseChatModel, R as BaseChatModelGemini1, f as BaseChatModelOptions, oe as BaseEmbeddingModel, re as BaseEmbeddingModelOptions, Uo as ChatModelBaseConfigDef, Fo as ChatModelBaseConfigSchema, qo as ChatModelC1ConfigDef, $o as ChatModelC1ConfigSchema, Bo as ChatModelReasoningConfigDef, zo as ChatModelReasoningConfigSchema, Ho as EmbeddingModelBaseConfigDef, Ao as EmbeddingModelBaseConfigSchema, ye as Gemini1_0Pro, ge as Gemini1_0ProLatest, ce as Gemini1_0ProLatestLiteral, Yo as Gemini1_0ProLatestOptions, ro as Gemini1_0ProLatestSchema, ue as Gemini1_0ProLiteral, Wo as Gemini1_0ProOptions, mo as Gemini1_0ProSchema, fe as Gemini1_0ProVision, he as Gemini1_0ProVisionLiteral, Jo as Gemini1_0ProVisionOptions, lo as Gemini1_0ProVisionSchema, pe as Gemini1_0Pro_001, de as Gemini1_0Pro_001Literal, Ko as Gemini1_0Pro_001Options, ao as Gemini1_0Pro_001Schema, Ee as Gemini1_5Flash, Te as Gemini1_5Flash001, Ce as Gemini1_5Flash001Literal, Xo as Gemini1_5Flash001Options, po as Gemini1_5Flash001Schema, Ge as Gemini1_5Flash002, Me as Gemini1_5Flash002Literal, Zo as Gemini1_5Flash002Options, co as Gemini1_5Flash002Schema, Pe as Gemini1_5FlashLatest, be as Gemini1_5FlashLatestLiteral, Qo as Gemini1_5FlashLatestOptions, go as Gemini1_5FlashLatestSchema, _e as Gemini1_5FlashLiteral, et as Gemini1_5FlashOptions, ho as Gemini1_5FlashSchema, Ne as Gemini1_5Pro, Se as Gemini1_5Pro001, Oe as Gemini1_5Pro001Literal, ot as Gemini1_5Pro001Options, fo as Gemini1_5Pro001Schema, Re as Gemini1_5Pro002, xe as Gemini1_5Pro002Literal, tt as Gemini1_5Pro002Options, uo as Gemini1_5Pro002Schema, we as Gemini1_5ProLatest, ke as Gemini1_5ProLatestLiteral, nt as Gemini1_5ProLatestOptions, yo as Gemini1_5ProLatestSchema, ve as Gemini1_5ProLiteral, it as Gemini1_5ProOptions, Co as Gemini1_5ProSchema, Le as Gemini2_0FlashExp, Ie as Gemini2_0FlashExpLiteral, st as Gemini2_0FlashExpOptions, To as Gemini2_0FlashExpSchema, Fe as Gemini2_5FlashPreview0417, De as Gemini2_5FlashPreview0417Literal, at as Gemini2_5FlashPreview0417Options, Mo as Gemini2_5FlashPreview0417Schema, $e as Gemini2_5ProPreview0325, Ue as Gemini2_5ProPreview0325Literal, rt as Gemini2_5ProPreview0325Options, Go as Gemini2_5ProPreview0325Schema, je as GeminiPro, Be as GeminiProLiteral, mt as GeminiProOptions, Po as GeminiProSchema, ze as GeminiProVision, qe as GeminiProVisionLiteral, lt as GeminiProVisionOptions, bo as GeminiProVisionSchema, K as Google, Jt as GoogleChatAssistantRoleLiteral, sn as GoogleChatContent, tn as GoogleChatContentPartFunctionCall, nn as GoogleChatContentPartFunctionResponse, on as GoogleChatContentPartInlineData, yt as GoogleChatContentPartText, ft as GoogleChatGenerationConfig, p as GoogleChatModelConfigs, G as GoogleChatModelModalities, b as GoogleChatModelModalitiesEnum, u as GoogleChatModelRoles, y as GoogleChatModelRolesMap, Bi as GoogleChatModelTextModalities, ji as GoogleChatModelTextModalitiesEnum, B as GoogleChatModelTextToolModalities, j as GoogleChatModelTextToolModalitiesEnum, We as GoogleChatModelTextVisionModalities, Xe as GoogleChatModelTextVisionModalitiesEnum, Ct as GoogleChatRequest, ut as GoogleChatSafetySettings, gt as GoogleChatSystemInstruction, an as GoogleChatTool, ht as GoogleChatToolConfig, Wt as GoogleChatToolRoleLiteral, ct as GoogleCompleteChatResponse, Xt as GoogleCompleteChatTextResponse, Zt as GoogleCompleteChatToolResponse, Z as GoogleEmbeddingModelConfigs, eo as GoogleEmbeddingModelModalities, oo as GoogleEmbeddingModelModalitiesEnum, St as GoogleEmbeddingRequest, Wn as GoogleEmbeddingRequestInput, Ot as GoogleGetEmbeddingsResponse, Ro as GoogleStreamChatResponse, Qt as GoogleStreamChatTextResponse, en as GoogleStreamChatToolResponse, jt as ProviderLiteral, Ae as Text_Embedding_001, _o as Text_Embedding_001Literal, dt as Text_Embedding_001Options, Eo as Text_Embedding_001Schema, He as Text_Embedding_004, Oo as Text_Embedding_004Literal, pt as Text_Embedding_004Options, So as Text_Embedding_004Schema, so as dimensions, J as frequencyPenalty, L as maxTokens, W as presencePenalty, io as reasoningEnabled, $ as safetySettings, X as seed, D as stop, I as temperature, U as toolChoice, Y as topK, F as topP };
|
|
17
17
|
//# sourceMappingURL=index.mjs.map
|
|
18
18
|
//# sourceMappingURL=index.mjs.map
|