@adaline/google 1.6.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ var types = require('@adaline/types');
|
|
|
6
6
|
|
|
7
7
|
var ct=Object.defineProperty,gt=Object.defineProperties;var ht=Object.getOwnPropertyDescriptors;var Co=Object.getOwnPropertySymbols;var ft=Object.prototype.hasOwnProperty,ut=Object.prototype.propertyIsEnumerable;var W=(r,e)=>(e=Symbol[r])?e:Symbol.for("Symbol."+r),yt=r=>{throw TypeError(r)};var To=(r,e,t)=>e in r?ct(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,P=(r,e)=>{for(var t in e||(e={}))ft.call(e,t)&&To(r,t,e[t]);if(Co)for(var t of Co(e))ut.call(e,t)&&To(r,t,e[t]);return r},N=(r,e)=>gt(r,ht(e));var S=(r,e,t)=>new Promise((o,i)=>{var l=a=>{try{n(t.next(a));}catch(s){i(s);}},m=a=>{try{n(t.throw(a));}catch(s){i(s);}},n=a=>a.done?o(a.value):Promise.resolve(a.value).then(l,m);n((t=t.apply(r,e)).next());}),Mo=function(r,e){this[0]=r,this[1]=e;},je=(r,e,t)=>{var o=(m,n,a,s)=>{try{var d=t[m](n),g=(n=d.value)instanceof Mo,C=d.done;Promise.resolve(g?n[0]:n).then(f=>g?o(m==="return"?m:"next",n[1]?{done:f.done,value:f.value}:f,a,s):a({value:f,done:C})).catch(f=>o("throw",f,a,s));}catch(f){s(f);}},i=m=>l[m]=n=>new Promise((a,s)=>o(m,n,a,s)),l={};return t=t.apply(r,e),l[W("asyncIterator")]=()=>l,i("next"),i("throw"),i("return"),l},bo=r=>{var e=r[W("asyncIterator")],t=!1,o,i={};return e==null?(e=r[W("iterator")](),o=l=>i[l]=m=>e[l](m)):(e=e.call(r),o=l=>i[l]=m=>{if(t){if(t=!1,l==="throw")throw m;return m}return t=!0,{done:!1,value:new Mo(new Promise(n=>{var a=e[l](m);a instanceof Object||yt("Object expected"),n(a);}),1)}}),i[W("iterator")]=()=>i,o("next"),"throw"in e?o("throw"):i.throw=l=>{throw l},"return"in e&&o("return"),i};var Be=(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}),qe=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}),Ae=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}),qn=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}),An=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}),zn=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}),Hn=provider.RangeConfigItem({param:"seed",title:provider.CHAT_CONFIG.SEED.title,description:provider.CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),He=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"]}),Ke=provider.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:zod.z.array(zod.z.object({threshold:zod.z.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]),category:zod.z.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"])}))}),Ye=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});var Q=(r,e,t,o,i)=>zod.z.object({temperature:Be(r,e).schema,maxTokens:qe(t).schema,stop:Ae(o).schema,topP:ze(i).schema,toolChoice:He.schema,safetySettings:Ke.schema}),ee=(r,e,t,o,i)=>({temperature:Be(r,e).def,maxTokens:qe(t).def,stop:Ae(o).def,topP:ze(i).def,toolChoice:He.def,safetySettings:Ke.def});var Go=provider.ObjectSchemaConfigItem({param:"response_schema",title:provider.CHAT_CONFIG.RESPONSE_SCHEMA.title,description:provider.CHAT_CONFIG.RESPONSE_SCHEMA.description,objectSchema:types.ResponseSchema}),_o=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"]}),te=(r,e,t,o,i)=>N(P({},ee(r,e,t,o,i)),{responseFormat:_o.def,responseSchema:Go.def}),ne=(r,e,t,o,i)=>Q(r,e,t,o,i).extend({responseFormat:_o.schema,responseSchema:Go.schema});var Po=(r,e,t,o,i)=>ne(r,e,t,o,i).extend({reasoningEnabled:Ye.schema}),So=(r,e,t,o,i)=>N(P({},te(r,e,t,o,i)),{reasoningEnabled:Ye.def});var Ve=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 Ro=r=>zod.z.object({dimensions:Ve(r).schema}),Oo=r=>({dimensions:Ve(r).def});var h={base:(r,e,t,o,i)=>({def:ee(r,e,t,o,i),schema:Q(r,e,t,o,i)}),responseSchema:(r,e,t,o,i)=>({def:te(r,e,t,o,i),schema:ne(r,e,t,o,i)}),reasoning:(r,e,t,o,i)=>({def:So(r,e,t,o,i),schema:Po(r,e,t,o,i)})},j={base:r=>({def:Oo(r),schema:Ro(r)})};var Ot="google",$=class{constructor(){this.version="v1";this.name=Ot;this.chatModelFactories={[ie]:{model:se,modelOptions:xo,modelSchema:Je},[ae]:{model:re,modelOptions:ko,modelSchema:Xe},[le]:{model:me,modelOptions:vo,modelSchema:We},[de]:{model:pe,modelOptions:Fo,modelSchema:Ze},[ce]:{model:ge,modelOptions:No,modelSchema:Qe},[he]:{model:fe,modelOptions:Io,modelSchema:eo},[ue]:{model:ye,modelOptions:Do,modelSchema:oo},[Ce]:{model:Te,modelOptions:Lo,modelSchema:to},[Me]:{model:be,modelOptions:Uo,modelSchema:no},[Ge]:{model:_e,modelOptions:$o,modelSchema:io},[Pe]:{model:Se,modelOptions:jo,modelSchema:so},[Ee]:{model:Re,modelOptions:Bo,modelSchema:ao},[Oe]:{model:we,modelOptions:qo,modelSchema:ro}};this.embeddingModelFactories={[lo]:{model:xe,modelOptions:Ao,modelSchema:mo},[po]:{model:ke,modelOptions:zo,modelSchema:co}};}chatModelLiterals(){return Object.keys(this.chatModelFactories)}chatModelSchemas(){return Object.keys(this.chatModelFactories).reduce((e,t)=>(e[t]=this.chatModelFactories[t].modelSchema,e),{})}chatModel(e){let t=e.modelName;if(!(t in this.chatModelFactories))throw new provider.ProviderError({info:`Google chat model: ${t} not found`,cause:new Error(`Google chat model: ${t} not found, available chat models:
|
|
8
8
|
[${this.chatModelLiterals().join(", ")}]`)});let o=this.chatModelFactories[t].model,i=this.chatModelFactories[t].modelOptions.parse(e);return new o(i)}embeddingModelLiterals(){return Object.keys(this.embeddingModelFactories)}embeddingModelSchemas(){return Object.keys(this.embeddingModelFactories).reduce((e,t)=>(e[t]=this.embeddingModelFactories[t].modelSchema,e),{})}embeddingModel(e){let t=e.modelName;if(!(t in this.embeddingModelFactories))throw new provider.ProviderError({info:`Google embedding model: ${t} not found`,cause:new Error(`Google embedding model: ${t} not found, available embedding models:
|
|
9
|
-
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,i=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(i)}};$.baseUrl="https://generativelanguage.googleapis.com/v1beta";var u={"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-2.5-flash":{modelName:"gemini-2.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.3,outputPricePerMillion:2.5}}}]}};var M=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),Nt="model",It="function",b={system:types.UserRoleLiteral,user:types.UserRoleLiteral,assistant:Nt,tool:It};var G=[types.TextModalityLiteral,types.ImageModalityLiteral,types.PdfModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],_=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.PdfModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]),Ri=[types.TextModalityLiteral],Oi=zod.z.enum([types.TextModalityLiteral]),wi=[types.TextModalityLiteral,types.ImageModalityLiteral],xi=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral]),ki=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],vi=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var Dt=zod.z.object({text:zod.z.string()}),Lt=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),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([Dt,Lt]))}).optional(),finishReason:zod.z.string(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number()}).optional()}),Ut=zod.z.object({text:zod.z.string()}),$t=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),ho=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([Ut,$t]))}).optional(),finishReason:zod.z.string().optional(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number().optional(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number().optional()}).optional()});var Wo=zod.z.object({text:zod.z.string().min(1)}),jt=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),Bt=zod.z.object({file_data:zod.z.object({mime_type:zod.z.string().min(1),file_uri:zod.z.string().min(1)})}),qt=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))})}),At=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),zt=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([Wo,jt,Bt,qt,At]))}),Yo=zod.z.object({parts:zod.z.array(Wo)}),Ht=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),Vo=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()})}),Jo=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()}),Xo=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"])}),Zo=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(zt),systemInstruction:Yo.optional(),system_instruction:Yo.optional(),generationConfig:Jo.optional(),generation_config:Jo.optional(),safetySettings:zod.z.array(Xo).optional(),safety_settings:zod.z.array(Xo).optional(),tools:zod.z.object({function_declarations:zod.z.array(Ht)}).optional(),toolConfig:Vo.optional(),tool_config:Vo.optional()});var T=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()}),y=class{constructor(e,t){this.version="v1";var i;let o=T.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash((i=o.baseUrl)!=null?i:$.baseUrl),this.completeChatUrl=provider.urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=provider.urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformPdfMessages(e){return S(this,null,function*(){let t=n=>S(this,null,function*(){let a={};provider.isRunningInBrowser()||(a["User-Agent"]="Mozilla/5.0 (compatible; GoogleFilesAPI/1.0)");let s=yield fetch(n,{headers:a});if(!s.ok)throw new provider.InvalidMessagesError({info:`Failed to download PDF from URL: ${n}`,cause:new Error(`HTTP ${s.status}: ${s.statusText}`)});let d=yield s.arrayBuffer();return new Uint8Array(d)}),o=n=>S(this,null,function*(){try{let a=yield fetch(`https://generativelanguage.googleapis.com/v1beta/files?key=${this.apiKey}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)return null;let g=((yield a.json()).files||[]).find(C=>C.displayName===n);return g?g.uri:null}catch(a){return null}}),i=(n,a)=>S(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:a}})});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 d=s.headers.get("x-goog-upload-url");if(!d)throw new provider.InvalidMessagesError({info:"No upload URL received from Google Files API",cause:new Error("Missing x-goog-upload-url header")});let g={"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"};provider.isRunningInBrowser()||(g["Content-Length"]=n.length.toString());let C=yield fetch(d,{method:"POST",headers:g,body:n});if(!C.ok)throw new provider.InvalidMessagesError({info:"Failed to upload PDF content to Google Files API",cause:new Error(`HTTP ${C.status}: ${C.statusText}`)});return (yield C.json()).file.uri}),l=n=>S(this,null,function*(){let a=yield o(n.providerCacheKey);if(a)return a;let s;if(n.value.type==="url")s=yield t(n.value.url);else {let d=n.value.base64,g="data:application/pdf;base64,";d=d.startsWith(g)?d.substring(g.length):d,s=provider.convertBase64ToUint8Array(d);}return yield i(s,n.providerCacheKey)}),m=[];for(let n of e){let a=[];for(let s of n.content)if(s.modality===types.PdfModalityLiteral){let d=yield l(s);a.push(N(P({},s),{value:{type:"url",url:d}}));}else a.push(s);m.push(N(P({},n),{content:a}));}return m})}transformModelRequest(e){let t=Zo.safeParse(e);if(!t.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,i=o.model;if(o.system_instruction&&o.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(o.generation_config&&o.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(o.tool_config&&o.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 l=o.system_instruction||o.systemInstruction,m=o.generation_config||o.generationConfig,n=o.safety_settings||o.safetySettings,a=o.tool_config||o.toolConfig;if(a&&(!o.tools||o.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={};a&&(a.function_calling_config.mode==="ANY"&&a.function_calling_config.allowed_function_names&&a.function_calling_config.allowed_function_names.length===1?s.toolChoice=a.function_calling_config.allowed_function_names[0]:s.toolChoice=a.function_calling_config.mode.toLowerCase()),s.seed=m==null?void 0:m.seed,s.maxTokens=m==null?void 0:m.maxOutputTokens,s.temperature=m==null?void 0:m.temperature,s.topP=m==null?void 0:m.topP,s.presencePenalty=m==null?void 0:m.presencePenalty,s.frequencyPenalty=m==null?void 0:m.frequencyPenalty,s.stop=m==null?void 0:m.stopSequences,s.safetySettings=n;let d=types.Config().parse(provider.removeUndefinedEntries(s)),g=[];l&&l.parts.forEach(f=>{g.push({role:types.SystemRoleLiteral,content:[{modality:types.TextModalityLiteral,value:f.text}]});}),o.contents.forEach(f=>{let w=f.role;switch(w){case"user":{let k=f.parts.map(E=>"text"in E?{modality:types.TextModalityLiteral,value:E.text}:{modality:types.ImageModalityLiteral,detail:"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:E.inline_data.data,mediaType:E.inline_data.mime_type.split("/")[1]}});g.push({role:w,content:k});}break;case"model":{let k=f.parts.map((E,F)=>"text"in E?{modality:types.TextModalityLiteral,value:E.text}:{modality:types.ToolCallModalityLiteral,id:F.toString(),index:F,name:E.function_call.name,arguments:JSON.stringify(E.function_call.args)});g.push({role:types.AssistantRoleLiteral,content:k});}break;case"function":{let k=f.parts.map((E,F)=>({modality:types.ToolResponseModalityLiteral,id:F.toString(),index:F,name:E.function_response.name,data:JSON.stringify(E.function_response.response)}));g.push({role:types.ToolRoleLiteral,content:k});}break;default:throw new provider.InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${f.role}' is not supported for model : ${this.modelName}`)})}});let C=[];return o.tools&&o.tools.function_declarations.forEach(f=>{C.push({type:"function",definition:{schema:{name:f.name,description:f.description,parameters:f.parameters}}});}),{modelName:i,config:d,messages:g,tools:C.length>0?C:void 0}}transformConfig(e,t,o){let i=e.toolChoice;delete e.toolChoice;let l=this.modelSchema.config.schema.safeParse(e);if(!l.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:l.error});let m=l.data;Object.keys(m).forEach(d=>{if(!(d in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${d}',
|
|
9
|
+
[${this.embeddingModelLiterals().join(", ")}]`)});let o=this.embeddingModelFactories[t].model,i=this.embeddingModelFactories[t].modelOptions.parse(e);return new o(i)}};$.baseUrl="https://generativelanguage.googleapis.com/v1beta";var u={"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-2.5-flash":{modelName:"gemini-2.5-flash",currency:"USD",tokenRanges:[{minTokens:0,maxTokens:null,prices:{base:{inputPricePerMillion:.3,outputPricePerMillion:2.5}}}]}};var M=zod.z.enum([types.SystemRoleLiteral,types.UserRoleLiteral,types.AssistantRoleLiteral,types.ToolRoleLiteral]),Nt="model",It="function",b={system:types.UserRoleLiteral,user:types.UserRoleLiteral,assistant:Nt,tool:It};var G=[types.TextModalityLiteral,types.ImageModalityLiteral,types.PdfModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],_=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral,types.PdfModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]),Ri=[types.TextModalityLiteral],Oi=zod.z.enum([types.TextModalityLiteral]),wi=[types.TextModalityLiteral,types.ImageModalityLiteral],xi=zod.z.enum([types.TextModalityLiteral,types.ImageModalityLiteral]),ki=[types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral],vi=zod.z.enum([types.TextModalityLiteral,types.ToolCallModalityLiteral,types.ToolResponseModalityLiteral]);var Dt=zod.z.object({text:zod.z.string()}),Lt=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),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([Dt,Lt]))}).optional(),finishReason:zod.z.string(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number()}).optional()}),Ut=zod.z.object({text:zod.z.string()}),$t=zod.z.object({functionCall:zod.z.object({name:zod.z.string(),args:zod.z.record(zod.z.any())})}),ho=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([Ut,$t]))}).optional(),finishReason:zod.z.string().optional(),index:zod.z.number().optional(),safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string(),blocked:zod.z.boolean().optional()})))})),promptFeedback:zod.z.optional(zod.z.object({safetyRatings:zod.z.optional(zod.z.array(zod.z.object({category:zod.z.string(),probability:zod.z.string()})))})),usageMetadata:zod.z.object({promptTokenCount:zod.z.number().optional(),cachedContentTokenCount:zod.z.number().optional(),candidatesTokenCount:zod.z.number().optional(),totalTokenCount:zod.z.number().optional()}).optional()});var Wo=zod.z.object({text:zod.z.string().min(1)}),jt=zod.z.object({inline_data:zod.z.object({mime_type:zod.z.string().min(1),data:zod.z.string().base64()})}),Bt=zod.z.object({file_data:zod.z.object({mime_type:zod.z.string().min(1),file_uri:zod.z.string().min(1)})}),qt=zod.z.object({function_call:zod.z.object({name:zod.z.string().min(1),args:zod.z.record(zod.z.string().min(1))})}),At=zod.z.object({function_response:zod.z.object({name:zod.z.string().min(1),response:zod.z.record(zod.z.string().min(1))})}),zt=zod.z.object({role:zod.z.enum(["user","model","function"]),parts:zod.z.array(zod.z.union([Wo,jt,Bt,qt,At]))}),Yo=zod.z.object({parts:zod.z.array(Wo)}),Ht=zod.z.object({name:zod.z.string().min(1),description:zod.z.string().min(1),parameters:zod.z.any()}),Vo=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()})}),Jo=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()}),Xo=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"])}),Zo=zod.z.object({model:zod.z.string().min(1).optional(),contents:zod.z.array(zt),systemInstruction:Yo.optional(),system_instruction:Yo.optional(),generationConfig:Jo.optional(),generation_config:Jo.optional(),safetySettings:zod.z.array(Xo).optional(),safety_settings:zod.z.array(Xo).optional(),tools:zod.z.object({function_declarations:zod.z.array(Ht)}).optional(),toolConfig:Vo.optional(),tool_config:Vo.optional()});var T=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()}),y=class{constructor(e,t){this.version="v1";var i;let o=T.parse(t);this.modelSchema=e,this.modelName=o.modelName,this.apiKey=o.apiKey,this.baseUrl=provider.urlWithoutTrailingSlash((i=o.baseUrl)!=null?i:$.baseUrl),this.completeChatUrl=provider.urlWithoutTrailingSlash(o.completeChatUrl||`${this.baseUrl}/models/${this.modelName}:generateContent?key=${this.apiKey}`),this.streamChatUrl=provider.urlWithoutTrailingSlash(o.streamChatUrl||`${this.baseUrl}/models/${this.modelName}:streamGenerateContent?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json"}}getDefaultParams(){return {}}getRetryDelay(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.reduce((t,o)=>t+o.content.map(i=>i.modality==="text"?i.value:"").join(" ").length,0)}transformPdfMessages(e){return S(this,null,function*(){let t=n=>S(this,null,function*(){let a={};provider.isRunningInBrowser()||(a["User-Agent"]="Mozilla/5.0 (compatible; GoogleFilesAPI/1.0)");let s=yield fetch(n,{headers:a});if(!s.ok)throw new provider.InvalidMessagesError({info:`Failed to download PDF from URL: ${n}`,cause:new Error(`HTTP ${s.status}: ${s.statusText}`)});let d=yield s.arrayBuffer();return new Uint8Array(d)}),o=n=>S(this,null,function*(){try{let a=yield fetch(`https://generativelanguage.googleapis.com/v1beta/files?key=${this.apiKey}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!a.ok)return null;let g=((yield a.json()).files||[]).find(C=>C.displayName===n);return g?g.uri:null}catch(a){return null}}),i=(n,a)=>S(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:a}})});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 d=s.headers.get("x-goog-upload-url");if(!d)throw new provider.InvalidMessagesError({info:"No upload URL received from Google Files API",cause:new Error("Missing x-goog-upload-url header")});let g={"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"};provider.isRunningInBrowser()||(g["Content-Length"]=n.length.toString());let C=yield fetch(d,{method:"POST",headers:g,body:n});if(!C.ok)throw new provider.InvalidMessagesError({info:"Failed to upload PDF content to Google Files API",cause:new Error(`HTTP ${C.status}: ${C.statusText}`)});return (yield C.json()).file.uri}),l=n=>S(this,null,function*(){let a=yield o(n.file.id);if(a)return a;let s;if(n.value.type==="url")s=yield t(n.value.url);else {let d=n.value.base64,g="data:application/pdf;base64,";d=d.startsWith(g)?d.substring(g.length):d,s=provider.convertBase64ToUint8Array(d);}return yield i(s,n.file.id)}),m=[];for(let n of e){let a=[];for(let s of n.content)if(s.modality===types.PdfModalityLiteral){let d=yield l(s);a.push(N(P({},s),{value:{type:"url",url:d}}));}else a.push(s);m.push(N(P({},n),{content:a}));}return m})}transformModelRequest(e){let t=Zo.safeParse(e);if(!t.success)throw new provider.InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,i=o.model;if(o.system_instruction&&o.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(o.generation_config&&o.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(o.tool_config&&o.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 l=o.system_instruction||o.systemInstruction,m=o.generation_config||o.generationConfig,n=o.safety_settings||o.safetySettings,a=o.tool_config||o.toolConfig;if(a&&(!o.tools||o.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={};a&&(a.function_calling_config.mode==="ANY"&&a.function_calling_config.allowed_function_names&&a.function_calling_config.allowed_function_names.length===1?s.toolChoice=a.function_calling_config.allowed_function_names[0]:s.toolChoice=a.function_calling_config.mode.toLowerCase()),s.seed=m==null?void 0:m.seed,s.maxTokens=m==null?void 0:m.maxOutputTokens,s.temperature=m==null?void 0:m.temperature,s.topP=m==null?void 0:m.topP,s.presencePenalty=m==null?void 0:m.presencePenalty,s.frequencyPenalty=m==null?void 0:m.frequencyPenalty,s.stop=m==null?void 0:m.stopSequences,s.safetySettings=n;let d=types.Config().parse(provider.removeUndefinedEntries(s)),g=[];l&&l.parts.forEach(f=>{g.push({role:types.SystemRoleLiteral,content:[{modality:types.TextModalityLiteral,value:f.text}]});}),o.contents.forEach(f=>{let w=f.role;switch(w){case"user":{let k=f.parts.map(E=>"text"in E?{modality:types.TextModalityLiteral,value:E.text}:{modality:types.ImageModalityLiteral,detail:"auto",value:{type:types.Base64ImageContentTypeLiteral,base64:E.inline_data.data,mediaType:E.inline_data.mime_type.split("/")[1]}});g.push({role:w,content:k});}break;case"model":{let k=f.parts.map((E,F)=>"text"in E?{modality:types.TextModalityLiteral,value:E.text}:{modality:types.ToolCallModalityLiteral,id:F.toString(),index:F,name:E.function_call.name,arguments:JSON.stringify(E.function_call.args)});g.push({role:types.AssistantRoleLiteral,content:k});}break;case"function":{let k=f.parts.map((E,F)=>({modality:types.ToolResponseModalityLiteral,id:F.toString(),index:F,name:E.function_response.name,data:JSON.stringify(E.function_response.response)}));g.push({role:types.ToolRoleLiteral,content:k});}break;default:throw new provider.InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${f.role}' is not supported for model : ${this.modelName}`)})}});let C=[];return o.tools&&o.tools.function_declarations.forEach(f=>{C.push({type:"function",definition:{schema:{name:f.name,description:f.description,parameters:f.parameters}}});}),{modelName:i,config:d,messages:g,tools:C.length>0?C:void 0}}transformConfig(e,t,o){let i=e.toolChoice;delete e.toolChoice;let l=this.modelSchema.config.schema.safeParse(e);if(!l.success)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:l.error});let m=l.data;Object.keys(m).forEach(d=>{if(!(d in this.modelSchema.config.def))throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${d}',
|
|
10
10
|
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let n=Object.keys(m).reduce((d,g)=>{let C=this.modelSchema.config.def[g],f=C.param,w=m[g];return g==="reasoningEnabled"?d.thinkingConfig={includeThoughts:w}:g==="maxReasoningTokens"?d.thinkingConfig=d.thinkingConfig&&typeof d.thinkingConfig=="object"?N(P({},d.thinkingConfig),{thinkingBudget:w}):{thinkingBudget:w}:f==="maxOutputTokens"&&C.type==="range"&&w===0?d[f]=C.max:d[f]=w,d},{}),a=n.safetySettings;delete n.safetySettings;let s;if(i!==void 0){let d=i;if(!o||o&&o.length===0)throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error("'tools' are required when 'toolChoice' is specified")});if(o&&o.length>0){let g=this.modelSchema.config.def.toolChoice;if(g.choices.includes(d))d==="any"?s={function_calling_config:{mode:"ANY",allowed_function_names:o.map(C=>C.definition.schema.name)}}:s={function_calling_config:{mode:d.toUpperCase()}};else if(o.map(C=>C.definition.schema.name).includes(d))s={function_calling_config:{mode:"ANY",allowed_function_names:[d]}};else throw new provider.InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${d}' is not part of provided 'tools' names or
|
|
11
11
|
one of [${g.choices.join(", ")}]`)})}}if("response_format"in n&&n.response_format!==void 0){let d=n.response_format;if(d==="json_schema"){let g=n.response_schema;if(!("response_schema"in n)||!n.response_schema||!(g!=null&&g.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=g.schema,n.responseMimeType="application/json","additionalProperties"in g.schema&&delete n.responseSchema.additionalProperties,delete n.response_format,delete n.response_schema;}else d==="json_object"?(n.responseSchema={type:"object"},delete n.response_format):d==="text"&&delete n.response_format;}return P(P({generation_config:n},s?{tool_config:s}:{}),a?{safety_settings:a}:{})}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let t=n=>{let a=n.match(/^data:(image\/[a-zA-Z]+|application\/pdf);base64,/);return a?n.substring(a[0].length):n},o=e.map(n=>{let a=types.Message().safeParse(n);if(!a.success)throw new provider.InvalidMessagesError({info:"Invalid messages",cause:a.error});return a.data});o.forEach(n=>{n.content.forEach(a=>{if(!this.modelSchema.modalities.includes(a.modality))throw new provider.InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support modality : '${a.modality}',
|
|
12
12
|
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),o.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}',
|