@adaline/google 0.2.0 → 0.3.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/README.md +0 -2
- package/dist/index.d.mts +415 -189
- package/dist/index.d.ts +415 -189
- package/dist/index.js +126 -120
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +10 -12
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -7
package/dist/index.mjs
CHANGED
|
@@ -2,18 +2,16 @@ import { z as z$1 } from 'zod';
|
|
|
2
2
|
import { RangeConfigItem, CHAT_CONFIG, SelectStringConfigItem, ObjectSchemaConfigItem, 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
|
|
7
|
-
[${this.
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),t.forEach(n=>{if(!Object.keys(this.modelSchema.roles).includes(n.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelSchema.name}'`,cause:new Error(`model : '${this.modelSchema.name}' does not support role : '${n.role}',
|
|
13
|
-
available
|
|
14
|
-
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),s[0].role!==this.modelSchema.roles[UserRoleLiteral])throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' requires first message to be from user`)});let m=n=>n===this.modelSchema.roles[UserRoleLiteral]||n===this.modelSchema.roles[ToolRoleLiteral]?[this.modelSchema.roles[AssistantRoleLiteral]]:[this.modelSchema.roles[UserRoleLiteral],this.modelSchema.roles[ToolRoleLiteral]];for(let n=1;n<s.length;n++)if(!m(s[n-1].role).includes(s[n].role))throw new InvalidMessagesError({info:`Invalid message format for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' cannot have message with role : '${s[n].role}' after message with role : '${s[n-1].role}'`)});if(s[s.length-1].role!==this.modelSchema.roles[UserRoleLiteral])throw new InvalidMessagesError({info:`Invalid message format for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' requires last message to be from user`)});return G({contents:s},o.parts.length>0?{system_instruction:o}:{})}transformTools(e){if(!this.modelSchema.modalities.includes(ToolCallModalityLiteral))throw new InvalidToolsError({info:`Invalid tool 'modality' for model : ${this.modelSchema.name}`,cause:new Error(`model : '${this.modelSchema.name}' does not support tool modality : '${ToolCallModalityLiteral}'`)});return !e||e&&e.length===0?{tools:[]}:{tools:e.map(s=>{let m=Tool().safeParse(s);if(!m.success)throw new InvalidToolsError({info:"Invalid tools",cause:m.error});return m.data}).map(s=>({function_declarations:[{name:s.definition.schema.name,description:s.definition.schema.description,parameters:s.definition.schema.parameters}]}))}}getCompleteChatUrl(e,t,o){return P(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(e,t,o){return P(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getCompleteChatData(e,t,o){return P(this,null,function*(){let s=this.transformConfig(e,t,o),m=this.transformMessages(t);if(m.messages&&m.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let n=o?this.transformTools(o):{};return new Promise(r=>{r(G(G(G(G({},this.getDefaultParams()),s),m),n));})})}transformCompleteChatResponse(e){let t=_o.safeParse(e);if(t.success){if(t.data.candidates.length===0)throw new ModelResponseError({info:"Invalid response from model",cause:new Error(`No choices in response : ${JSON.stringify(t.data)}`)});let o=t.data,s=[],m,n=o.candidates[0].content;if(n){let c=n.parts.map((p,T)=>{if("text"in p&&p.text!==void 0)return createTextContent(p.text);if("functionCall"in p&&p.functionCall!==void 0)return createToolCallContent(T,`${p.functionCall.name}_${T}`,p.functionCall.name,JSON.stringify(p.functionCall.args))});return s.push({role:AssistantRoleLiteral,content:c}),o.usageMetadata&&(m={promptTokens:o.usageMetadata.promptTokenCount,totalTokens:o.usageMetadata.totalTokenCount,completionTokens:o.usageMetadata.candidatesTokenCount||0}),{messages:s,usage:m,logProbs:void 0}}let r=o.candidates[0].safetyRatings;if(r&&r.length>0&&r.forEach(c=>{if(c.blocked)throw new ModelResponseError({info:`Blocked content for category: ${c.category} with probability: ${c.probability}`,cause:new Error(`Blocked content for category: ${c.category} with probability: ${c.probability}`)})}),o.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:t.error})}getStreamChatUrl(e,t,o){return P(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getStreamChatHeaders(e,t,o){return P(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getStreamChatData(e,t,o){return P(this,null,function*(){let s=this.transformConfig(e,t,o),m=this.transformMessages(t);if(m.messages&&m.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let n=o?this.transformTools(o):{};return new Promise(r=>{r(G(G(G(G({},this.getDefaultParams()),s),m),n));})})}transformStreamChatResponseChunk(e,t){return ho(this,null,function*(){let o=(t+e).split(",\r").filter(s=>s.trim()!=="");for(let s of o){let m=s;if(m=m.replace(/\n/g,""),m.startsWith("["))m=m.slice(1);else if(m.endsWith("]")){if(m==="]")return;m=m.slice(0,-1);}let n;try{n=JSON.parse(m);}catch(l){if(l instanceof SyntaxError){t=m;continue}else throw l}t="";let r=Eo.safeParse(n);if(r.success){let l={partialMessages:[]},c=r.data;if(c.candidates.length>0){let p=c.candidates[0].content;p&&"parts"in p&&p.parts.length>0&&p.parts.forEach((T,b)=>{if("text"in T&&T.text!==void 0&&l.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,T.text)),"functionCall"in T&&T.functionCall!==void 0){let f=T.functionCall;l.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,b,`${f.name}_${b}`,f.name,JSON.stringify(f.args)));}});}c.usageMetadata&&(l.usage={promptTokens:c.usageMetadata.promptTokenCount,completionTokens:c.usageMetadata.candidatesTokenCount,totalTokens:c.usageMetadata.totalTokenCount}),yield {partialResponse:l,buffer:t};}else throw new ModelResponseError({info:"Invalid response from model",cause:r.error})}yield {partialResponse:{partialMessages:[]},buffer:t};})}};var R=class extends C{transformMessages(e){let t=super.transformMessages(e);if(t.systemInstruction){let o={role:this.modelSchema.roles[UserRoleLiteral],parts:t.systemInstruction.parts};t.contents.unshift(o),delete t.systemInstruction;}return t}};var Le="gemini-1.0-pro",jt="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(u,D).parse({name:Le,description:jt,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:z,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),wo=g,ae=class extends R{constructor(e){super(ve,e);}};var Ie="gemini-1.0-pro-001",Dt="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",$e=ChatModelSchema(u,D).parse({name:Ie,description:Dt,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:z,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),ko=g,re=class extends R{constructor(e){super($e,e);}};var Fe="gemini-1.0-pro-latest",Bt="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",qe=ChatModelSchema(u,D).parse({name:Fe,description:Bt,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:z,config:{def:h.base(1,.9,2048,4,1).def,schema:h.base(1,.9,2048,4,1).schema}}),Lo=g,le=class extends R{constructor(e){super(qe,e);}};var je="gemini-1.0-pro-vision",At="Google's predecessor to Gemini 1.5 Pro, an image understanding model to handle a broad range of applications",ze=ChatModelSchema(u,Mo).parse({name:je,description:At,maxInputTokens:12288,maxOutputTokens:4096,roles:y,modalities:bo,config:{def:h.c1(1,.4,4096,4,1,32).def,schema:h.c1(1,.4,4096,4,1,32).schema}}),vo=g,me=class extends R{constructor(e){super(ze,e);}};var De="gemini-1.5-flash",Vt="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",Ue=ChatModelSchema(u,E).parse({name:De,description:Vt,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Io=g,de=class extends C{constructor(e){super(Ue,e);}};var Be="gemini-1.5-flash-001",Yt="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",Ne=ChatModelSchema(u,E).parse({name:Be,description:Yt,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),$o=g,pe=class extends C{constructor(e){super(Ne,e);}};var Ae="gemini-1.5-flash-002",Wt="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",He=ChatModelSchema(u,E).parse({name:Ae,description:Wt,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,40).def,schema:h.c1(2,1,8192,4,.95,40).schema}}),Fo=g,ce=class extends C{constructor(e){super(He,e);}};var Ve="gemini-1.5-flash-latest",Qt="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",Ke=ChatModelSchema(u,E).parse({name:Ve,description:Qt,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),qo=g,he=class extends C{constructor(e){super(Ke,e);}};var Ye="gemini-1.5-pro",en="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Je=ChatModelSchema(u,E).parse({name:Ye,description:en,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),jo=g,fe=class extends C{constructor(e){super(Je,e);}};var We="gemini-1.5-pro-001",tn="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Xe=ChatModelSchema(u,E).parse({name:We,description:tn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),zo=g,ge=class extends C{constructor(e){super(Xe,e);}};var Qe="gemini-1.5-pro-002",sn="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",Ze=ChatModelSchema(u,E).parse({name:Qe,description:sn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,40).def,schema:h.c1(2,1,8192,4,.95,40).schema}}),Do=g,ue=class extends C{constructor(e){super(Ze,e);}};var eo="gemini-1.5-pro-latest",rn="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",oo=ChatModelSchema(u,E).parse({name:eo,description:rn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:h.c1(2,1,8192,4,.95,64).def,schema:h.c1(2,1,8192,4,.95,64).schema}}),Uo=g,ye=class extends C{constructor(e){super(oo,e);}};var _e=[EmbeddingTextModalityLiteral],Ee=z$1.enum([EmbeddingTextModalityLiteral]);var Jo=z$1.object({embeddings:z$1.array(z$1.object({values:z$1.array(z$1.number())}))});var mn=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)})}),Wo=z$1.object({model:z$1.string().min(1).optional(),requests:z$1.array(mn).min(1),outputDimensionality:z$1.number().int().min(1).optional()});var Z=z$1.object({apiKey:z$1.string(),baseUrl:z$1.string().url(),getEmbeddingsUrl:z$1.string().url().optional()}),N=class{constructor(e,t){this.version="v1";let o=Z.parse(t);this.modelSchema=e,this.apiKey=o.apiKey,this.baseUrl=urlWithoutTrailingSlash(o.baseUrl),this.getEmbeddingsUrl=urlWithoutTrailingSlash(o.getEmbeddingsUrl||`${this.baseUrl}/models/${this.modelSchema.name}:batchEmbedContents?key=${this.apiKey}`);}getDefaultBaseUrl(){return this.baseUrl}getDefaultHeaders(){return {"Content-Type":"application/json",source:"adaline.ai"}}getDefaultParams(){return {model:this.modelSchema.name}}getRetryDelay(e){return {shouldRetry:!1,delayMs:0}}getTokenCount(e){return e.requests.reduce((t,o)=>t+o.length,0)}transformModelRequest(e){let t=Wo.safeParse(e);if(!t.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:t.error});let o=t.data,s=o.model,m={outputDimensionality:o.outputDimensionality},n=Config().parse(removeUndefinedEntries(m)),r={modality:EmbeddingTextModalityLiteral,requests:o.requests.reduce((l,c)=>(l.push(...c.content.parts.map(p=>p.text)),l),[])};return {modelName:s,config:n,embeddingRequests:r}}transformConfig(e,t){let o=this.modelSchema.config.schema.safeParse(e);if(!o.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:o.error});let s=o.data;return Object.keys(s).forEach(n=>{if(!this.modelSchema.config.def[n])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelSchema.name}'`,cause:new Error(`Invalid config key : '${n}',
|
|
15
|
-
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((n,r)=>{let c=this.modelSchema.config.def[r].param,p=s[r];return n[c]=p,n},{})}transformEmbeddingRequests(e){let t=EmbeddingRequests().safeParse(e);if(!t.success)throw new InvalidEmbeddingRequestsError({info:"Invalid embedding requests",cause:t.error});if(e.modality!==EmbeddingTextModalityLiteral)throw new InvalidEmbeddingRequestsError({info:`Invalid embedding requests for model : '${this.modelSchema.name}'`,cause:new Error(`Only '${EmbeddingTextModalityLiteral}' modality is supported for model : '${this.modelSchema.name}'`)});return {requests:t.data.requests.map(s=>({model:`models/${this.modelSchema.name}`,content:{parts:[{text:s}]}}))}}getGetEmbeddingsUrl(e,t){return P(this,null,function*(){return new Promise(o=>{o(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,t){return P(this,null,function*(){return new Promise(o=>{o(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,t){return P(this,null,function*(){return new Promise(o=>{let s=this.transformConfig(e),m=this.transformEmbeddingRequests(t);if(t.requests.length===0)throw new InvalidEmbeddingRequestsError({info:`Invalid embedding requests for model : '${this.modelSchema.name}'`,cause:new Error("requests cannot be empty")});s.outputDimensionality&&(m.requests.forEach(n=>{n.outputDimensionality=s.outputDimensionality;}),delete s.outputDimensionality),o(G(G(G({},this.getDefaultParams()),s),m));})})}transformGetEmbeddingsResponse(e){let t=Jo.safeParse(e);if(t.success){let s=t.data.embeddings.map((m,n)=>({index:n,embedding:m.values}));return {encodingFormat:FloatEmbeddingLiteral,embeddings:s}}throw new ModelResponseError({info:"Invalid response from model",cause:t.error})}};var to="text-embedding-001",yn="text-embedding-001",no=EmbeddingModelSchema(Ee).parse({name:to,description:yn,modalities:_e,maxInputTokens:2048,maxOutputTokens:768,config:{def:j.base(768).def,schema:j.base(768).schema}}),Bo=Z,Ce=class extends N{constructor(e){super(no,e);}};var so="text-embedding-004",Tn="text-embedding-004",io=EmbeddingModelSchema(Ee).parse({name:so,description:Tn,modalities:_e,maxInputTokens:2048,maxOutputTokens:768,config:{def:j.base(768).def,schema:j.base(768).schema}}),No=Z,Te=class extends N{constructor(e){super(io,e);}};
|
|
5
|
+
var mt=Object.defineProperty,dt=Object.defineProperties;var pt=Object.getOwnPropertyDescriptors;var Go=Object.getOwnPropertySymbols;var ct=Object.prototype.hasOwnProperty,ft=Object.prototype.propertyIsEnumerable;var ht=(i,e)=>(e=Symbol[i])?e:Symbol.for("Symbol."+i);var Mo=(i,e,o)=>e in i?mt(i,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):i[e]=o,G=(i,e)=>{for(var o in e||(e={}))ct.call(e,o)&&Mo(i,o,e[o]);if(Go)for(var o of Go(e))ft.call(e,o)&&Mo(i,o,e[o]);return i},we=(i,e)=>dt(i,pt(e));var R=(i,e,o)=>new Promise((t,s)=>{var r=l=>{try{m(o.next(l));}catch(p){s(p);}},n=l=>{try{m(o.throw(l));}catch(p){s(p);}},m=l=>l.done?t(l.value):Promise.resolve(l.value).then(r,n);m((o=o.apply(i,e)).next());}),gt=function(i,e){this[0]=i,this[1]=e;},bo=(i,e,o)=>{var t=(n,m,l,p)=>{try{var f=o[n](m),C=(m=f.value)instanceof gt,M=f.done;Promise.resolve(C?m[0]:m).then(g=>C?t(n==="return"?n:"next",m[1]?{done:g.done,value:g.value}:g,l,p):l({value:g,done:M})).catch(g=>t("throw",g,l,p));}catch(g){p(g);}},s=n=>r[n]=m=>new Promise((l,p)=>t(n,m,l,p)),r={};return o=o.apply(i,e),r[ht("asyncIterator")]=()=>r,s("next"),s("throw"),s("return"),r};var N=(i,e)=>RangeConfigItem({param:"temperature",title:CHAT_CONFIG.TEMPERATURE.title,description:CHAT_CONFIG.TEMPERATURE.description,min:0,max:i,step:.01,default:e}),v=i=>RangeConfigItem({param:"maxOutputTokens",title:CHAT_CONFIG.MAX_TOKENS.title,description:CHAT_CONFIG.MAX_TOKENS.description,min:0,max:i,step:1,default:0}),q=i=>MultiStringConfigItem({param:"stopSequences",title:CHAT_CONFIG.STOP(i).title,description:CHAT_CONFIG.STOP(i).description,max:i}),F=i=>RangeConfigItem({param:"topP",title:CHAT_CONFIG.TOP_P.title,description:CHAT_CONFIG.TOP_P.description,min:0,max:1,step:.01,default:i}),Le=i=>RangeConfigItem({param:"topK",title:CHAT_CONFIG.TOP_K.title,description:CHAT_CONFIG.TOP_K.description,min:1,max:40,step:1,default:i}),Ie=RangeConfigItem({param:"frequencyPenalty",title:CHAT_CONFIG.FREQUENCY_PENALTY.title,description:CHAT_CONFIG.FREQUENCY_PENALTY.description,min:-2,max:2,step:.01,default:0}),ke=RangeConfigItem({param:"presencePenalty",title:CHAT_CONFIG.PRESENCE_PENALTY.title,description:CHAT_CONFIG.PRESENCE_PENALTY.description,min:-2,max:2,step:.01,default:0}),Ne=RangeConfigItem({param:"seed",title:CHAT_CONFIG.SEED.title,description:CHAT_CONFIG.SEED.description,min:0,max:1e6,step:1,default:0}),$=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"]}),z=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$1.array(z$1.object({threshold:z$1.enum(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]),category:z$1.enum(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_CIVIC_INTEGRITY"])}))});var _o=(i,e,o,t,s)=>z$1.object({temperature:N(i,e).schema,maxTokens:v(o).schema,stop:q(t).schema,topP:F(s).schema,toolChoice:$.schema,safetySettings:z.schema}),Eo=(i,e,o,t,s)=>({temperature:N(i,e).def,maxTokens:v(o).def,stop:q(t).def,topP:F(s).def,toolChoice:$.def,safetySettings:z.def});var Oo=(i,e,o,t,s,r)=>z$1.object({temperature:N(i,e).schema,maxTokens:v(o).schema,stop:q(t).schema,topP:F(s).schema,topK:Le(r).schema,frequencyPenalty:Ie.schema,presencePenalty:ke.schema,seed:Ne.schema.transform(n=>n===0?void 0:n),toolChoice:$.schema,safetySettings:z.schema}),Po=(i,e,o,t,s,r)=>({temperature:N(i,e).def,maxTokens:v(o).def,stop:q(t).def,topP:F(s).def,topK:Le(r).def,frequencyPenalty:Ie.def,presencePenalty:ke.def,seed:Ne.def,toolChoice:$.def,safetySettings:z.def});var ve=i=>RangeConfigItem({param:"outputDimensionality",title:EMBEDDING_CONFIG.DIMENSIONS.title,description:EMBEDDING_CONFIG.DIMENSIONS.description,min:1,max:i,step:1,default:i});var Ro=i=>z$1.object({dimensions:ve(i).schema}),xo=i=>({dimensions:ve(i).def});var c={base:(i,e,o,t,s)=>({def:Eo(i,e,o,t,s),schema:_o(i,e,o,t,s)}),c1:(i,e,o,t,s,r)=>({def:Po(i,e,o,t,s,r),schema:Oo(i,e,o,t,s,r)})},j={base:i=>({def:xo(i),schema:Ro(i)})};var u=z$1.enum([SystemRoleLiteral,UserRoleLiteral,AssistantRoleLiteral,ToolRoleLiteral]),St="model",Rt="function",y={system:UserRoleLiteral,user:UserRoleLiteral,assistant:St,tool:Rt};var _=[TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],E=z$1.enum([TextModalityLiteral,ImageModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]),is=[TextModalityLiteral],as=z$1.enum([TextModalityLiteral]),ae=[TextModalityLiteral,ImageModalityLiteral],re=z$1.enum([TextModalityLiteral,ImageModalityLiteral]),L=[TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral],I=z$1.enum([TextModalityLiteral,ToolCallModalityLiteral,ToolResponseModalityLiteral]);var xt=z$1.object({text:z$1.string()}),wt=z$1.object({functionCall:z$1.object({name:z$1.string(),args:z$1.record(z$1.any())})}),wo=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([xt,wt]))}).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()}),Lt=z$1.object({text:z$1.string()}),It=z$1.object({functionCall:z$1.object({name:z$1.string(),args:z$1.record(z$1.any())})}),Lo=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([Lt,It]))}).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(),cachedContentTokenCount:z$1.number().optional(),candidatesTokenCount:z$1.number(),totalTokenCount:z$1.number()}).optional()});var qo=z$1.object({text:z$1.string().min(1)}),kt=z$1.object({inline_data:z$1.object({mime_type:z$1.string().min(1),data:z$1.string().base64()})}),Nt=z$1.object({function_call:z$1.object({name:z$1.string().min(1),args:z$1.record(z$1.string().min(1))})}),vt=z$1.object({function_response:z$1.object({name:z$1.string().min(1),response:z$1.record(z$1.string().min(1))})}),qt=z$1.object({role:z$1.enum(["user","model","function"]),parts:z$1.array(z$1.union([qo,kt,Nt,vt]))}),Io=z$1.object({parts:z$1.array(qo)}),Ft=z$1.object({name:z$1.string().min(1),description:z$1.string().min(1),parameters:z$1.any()}),ko=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()})}),No=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()}),vo=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"])}),Fo=z$1.object({model:z$1.string().min(1).optional(),contents:z$1.array(qt),systemInstruction:Io.optional(),system_instruction:Io.optional(),generationConfig:No.optional(),generation_config:No.optional(),safetySettings:z$1.array(vo).optional(),safety_settings:z$1.array(vo).optional(),tools:z$1.object({function_declarations:z$1.array(Ft)}).optional(),toolConfig:ko.optional(),tool_config:ko.optional()});var $t="google",Y=class{constructor(){this.version="v1";this.name=$t;this.chatModelFactories={[Fe]:{model:me,modelOptions:$o,modelSchema:$e},[ze]:{model:de,modelOptions:zo,modelSchema:je},[Xe]:{model:ue,modelOptions:Vo,modelSchema:Qe},[Ze]:{model:ye,modelOptions:Ho,modelSchema:eo},[oo]:{model:Ce,modelOptions:Ko,modelSchema:to},[Je]:{model:ge,modelOptions:Ao,modelSchema:We},[io]:{model:Ge,modelOptions:Jo,modelSchema:ao},[ro]:{model:Me,modelOptions:Wo,modelSchema:lo},[mo]:{model:be,modelOptions:Xo,modelSchema:po},[no]:{model:Te,modelOptions:Yo,modelSchema:so},[Be]:{model:pe,modelOptions:jo,modelSchema:De},[Ke]:{model:he,modelOptions:Uo,modelSchema:Ye},[Ve]:{model:fe,modelOptions:Do,modelSchema:He},[Ue]:{model:ce,modelOptions:Bo,modelSchema:Ae}};this.embeddingModelFactories={[co]:{model:_e,modelOptions:Qo,modelSchema:fo},[ho]:{model:Ee,modelOptions:Zo,modelSchema:go}};}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)throw new ProviderError({info:"Google chat model name is required",cause:new Error("Google chat model name is required")});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,s=we(G({},e),{modelName:o}),r=this.chatModelFactories[o].modelOptions.parse(s);return new t(r)}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)throw new ProviderError({info:"Google embedding model name is required",cause:new Error("Google embedding model name is required")});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,s=we(G({},e),{modelName:o}),r=this.embeddingModelFactories[o].modelOptions.parse(s);return new t(r)}};Y.baseUrl="https://generativelanguage.googleapis.com/v1beta";var h=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=h.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash((s=t.baseUrl)!=null?s:Y.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",source:"adaline.ai"}}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=Fo.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 r=t.system_instruction||t.systemInstruction,n=t.generation_config||t.generationConfig,m=t.safety_settings||t.safetySettings,l=t.tool_config||t.toolConfig;if(l&&(!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 p={};l&&(l.function_calling_config.mode==="ANY"&&l.function_calling_config.allowed_function_names&&l.function_calling_config.allowed_function_names.length===1?p.toolChoice=l.function_calling_config.allowed_function_names[0]:p.toolChoice=l.function_calling_config.mode.toLowerCase()),p.seed=n==null?void 0:n.seed,p.maxTokens=n==null?void 0:n.maxOutputTokens,p.temperature=n==null?void 0:n.temperature,p.topP=n==null?void 0:n.topP,p.presencePenalty=n==null?void 0:n.presencePenalty,p.frequencyPenalty=n==null?void 0:n.frequencyPenalty,p.stop=n==null?void 0:n.stopSequences,p.safetySettings=m;let f=Config().parse(removeUndefinedEntries(p)),C=[];r&&r.parts.forEach(g=>{C.push({role:SystemRoleLiteral,content:[{modality:TextModalityLiteral,value:g.text}]});}),t.contents.forEach(g=>{let V=g.role;switch(V){case"user":{let H=g.parts.map(S=>"text"in S?{modality:TextModalityLiteral,value:S.text}:{modality:ImageModalityLiteral,detail:"auto",value:{type:Base64ImageContentTypeLiteral,base64:S.inline_data.data,media_type:S.inline_data.mime_type.split("/")[1]}});C.push({role:V,content:H});}break;case"model":{let H=g.parts.map((S,K)=>"text"in S?{modality:TextModalityLiteral,value:S.text}:{modality:ToolCallModalityLiteral,id:K.toString(),index:K,name:S.function_call.name,arguments:JSON.stringify(S.function_call.args)});C.push({role:AssistantRoleLiteral,content:H});}break;case"function":{let H=g.parts.map((S,K)=>({modality:ToolResponseModalityLiteral,id:K.toString(),index:K,name:S.function_response.name,data:JSON.stringify(S.function_response.response)}));C.push({role:ToolRoleLiteral,content:H});}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:f,messages:C,tools:M.length>0?M:void 0}}transformConfig(e,o,t){let s=e.toolChoice;delete e.toolChoice;let r=this.modelSchema.config.schema.safeParse(e);if(!r.success)throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:r.error});let n=r.data;Object.keys(n).forEach(f=>{if(!(f in this.modelSchema.config.def))throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${f}',
|
|
8
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})});let m=Object.keys(n).reduce((f,C)=>{let M=this.modelSchema.config.def[C],g=M.param,V=n[C];return g==="maxOutputTokens"&&M.type==="range"&&V===0?f[g]=M.max:f[g]=V,f},{}),l=m.safetySettings;delete m.safetySettings;let p;if(s!==void 0){let f=s;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 C=this.modelSchema.config.def.toolChoice;if(C.choices.includes(f))f==="any"?p={function_calling_config:{mode:"ANY",allowed_function_names:t.map(M=>M.definition.schema.name)}}:p={function_calling_config:{mode:f.toUpperCase()}};else if(t.map(M=>M.definition.schema.name).includes(f))p={function_calling_config:{mode:"ANY",allowed_function_names:[f]}};else throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`toolChoice : '${f}' is not part of provided 'tools' names or
|
|
9
|
+
one of [${C.choices.join(", ")}]`)})}}return G(G({generation_config:m},p?{tool_config:p}:{}),l?{safety_settings:l}:{})}transformMessages(e){if(!e||e&&e.length===0)return {messages:[]};let o=e.map(n=>{let m=Message().safeParse(n);if(!m.success)throw new InvalidMessagesError({info:"Invalid messages",cause:m.error});return m.data});o.forEach(n=>{n.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
|
+
available modalities : [${this.modelSchema.modalities.join(", ")}]`)})});}),o.forEach(n=>{if(!Object.keys(this.modelSchema.roles).includes(n.role))throw new InvalidMessagesError({info:`Invalid message content for model : '${this.modelName}'`,cause:new Error(`model : '${this.modelName}' does not support role : '${n.role}',
|
|
11
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})});let t={parts:[]},s=[];if(o.forEach(n=>{switch(n.role){case SystemRoleLiteral:n.content.forEach(m=>{if(m.modality===TextModalityLiteral)t.parts.push({text:m.value});else throw new InvalidMessagesError({info:`Invalid message 'role' and 'modality' combination for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' cannot have content with modality : '${m.modality}'`)})});break;case AssistantRoleLiteral:{let m=[];n.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 : '${n.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[n.role],parts:m});}break;case UserRoleLiteral:{let m=[];n.content.forEach(l=>{if(l.modality===TextModalityLiteral)m.push({text:l.value});else if(l.modality===ImageModalityLiteral){if(l.value.type==="base64")m.push({inline_data:{mime_type:l.value.media_type,data:l.value.base64}});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 : '${n.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[n.role],parts:m});}break;case ToolRoleLiteral:{let m=[];n.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 : '${n.role}' cannot have content with modality : '${l.modality}'`)})}),s.push({role:this.modelSchema.roles[n.role],parts:m});}break;default:throw new InvalidMessagesError({info:`Invalid message 'role' for model : ${this.modelName}`,cause:new Error(`role : '${n.role}' is not supported,
|
|
12
|
+
available roles : [${Object.keys(this.modelSchema.roles).join(", ")}]`)})}}),s[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 r=n=>n===this.modelSchema.roles[UserRoleLiteral]||n===this.modelSchema.roles[ToolRoleLiteral]?[this.modelSchema.roles[AssistantRoleLiteral]]:[this.modelSchema.roles[UserRoleLiteral],this.modelSchema.roles[ToolRoleLiteral]];for(let n=1;n<s.length;n++)if(!r(s[n-1].role).includes(s[n].role))throw new InvalidMessagesError({info:`Invalid message format for model : ${this.modelName}`,cause:new Error(`model : '${this.modelName}' cannot have message with role : '${s[n].role}' after message with role : '${s[n-1].role}'`)});if(s[s.length-1].role!==this.modelSchema.roles[UserRoleLiteral])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 G({contents:s},t.parts.length>0?{system_instruction:t}:{})}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:e.map(s=>{let r=Tool().safeParse(s);if(!r.success)throw new InvalidToolsError({info:"Invalid tools",cause:r.error});return r.data}).map(s=>({function_declarations:[{name:s.definition.schema.name,description:s.definition.schema.description,parameters:s.definition.schema.parameters}]}))}}getCompleteChatUrl(e,o,t){return R(this,null,function*(){return new Promise(s=>{s(this.completeChatUrl);})})}getCompleteChatHeaders(e,o,t){return R(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getCompleteChatData(e,o,t){return R(this,null,function*(){let s=this.transformConfig(e,o,t),r=this.transformMessages(o);if(r.messages&&r.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let n=t?this.transformTools(t):{};return new Promise(m=>{m(G(G(G(G({},this.getDefaultParams()),s),r),n));})})}transformCompleteChatResponse(e){let o=wo.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,s=[],r,n=t.candidates[0].content;if(n){let p=n.parts.map((f,C)=>{if("text"in f&&f.text!==void 0)return createTextContent(f.text);if("functionCall"in f&&f.functionCall!==void 0)return createToolCallContent(C,`${f.functionCall.name}_${C}`,f.functionCall.name,JSON.stringify(f.functionCall.args))});return s.push({role:AssistantRoleLiteral,content:p}),t.usageMetadata&&(r={promptTokens:t.usageMetadata.promptTokenCount,totalTokens:t.usageMetadata.totalTokenCount,completionTokens:t.usageMetadata.candidatesTokenCount||0}),{messages:s,usage:r,logProbs:void 0}}let m=t.candidates[0].safetyRatings;if(m&&m.length>0&&m.forEach(p=>{if(p.blocked)throw new ModelResponseError({info:`Blocked content for category: ${p.category} with probability: ${p.probability}`,cause:new Error(`Blocked content for category: ${p.category} with probability: ${p.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 R(this,null,function*(){return new Promise(s=>{s(this.streamChatUrl);})})}getStreamChatHeaders(e,o,t){return R(this,null,function*(){return new Promise(s=>{s(this.getDefaultHeaders());})})}getStreamChatData(e,o,t){return R(this,null,function*(){let s=this.transformConfig(e,o,t),r=this.transformMessages(o);if(r.messages&&r.messages.length===0)throw new InvalidMessagesError({info:"Messages are required",cause:new Error("Messages are required")});let n=t?this.transformTools(t):{};return new Promise(m=>{m(G(G(G(G({},this.getDefaultParams()),s),r),n));})})}transformStreamChatResponseChunk(e,o){return bo(this,null,function*(){let t=(o+e).split(",\r").filter(s=>s.trim()!=="");for(let s of t){let r=s;if(r=r.replace(/\n/g,""),r.startsWith("["))r=r.slice(1);else if(r.endsWith("]")){if(r==="]")return;r=r.slice(0,-1);}let n;try{n=JSON.parse(r);}catch(l){if(l instanceof SyntaxError){o=r;continue}else throw l}o="";let m=Lo.safeParse(n);if(m.success){let l={partialMessages:[]},p=m.data;if(p.candidates.length>0){let f=p.candidates[0].content;f&&"parts"in f&&f.parts.length>0&&f.parts.forEach((C,M)=>{if("text"in C&&C.text!==void 0&&l.partialMessages.push(createPartialTextMessage(AssistantRoleLiteral,C.text)),"functionCall"in C&&C.functionCall!==void 0){let g=C.functionCall;l.partialMessages.push(createPartialToolCallMessage(AssistantRoleLiteral,M,`${g.name}_${M}`,g.name,JSON.stringify(g.args)));}});}p.usageMetadata&&(l.usage={promptTokens:p.usageMetadata.promptTokenCount,completionTokens:p.usageMetadata.candidatesTokenCount,totalTokens:p.usageMetadata.totalTokenCount}),yield {partialResponse:l,buffer:o};}else throw new ModelResponseError({info:"Invalid response from model",cause:m.error})}yield {partialResponse:{partialMessages:[]},buffer:o};})}};var P=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 Fe="gemini-pro",Wt="A model for scaling across a wide range of tasks Optimized for natural language tasks, multi-turn text and code chat, and code generation",$e=ChatModelSchema(u,I).parse({name:Fe,description:Wt,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:L,config:{def:c.base(1,.9,2048,4,1).def,schema:c.base(1,.9,2048,4,1).schema}}),$o=h,me=class extends P{constructor(e){super($e,e);}};var ze="gemini-pro-vision",Qt="An image understanding model to handle a broad range of applications",je=ChatModelSchema(u,re).parse({name:ze,description:Qt,maxInputTokens:12288,maxOutputTokens:4096,roles:y,modalities:ae,config:{def:c.c1(1,.4,4096,4,1,32).def,schema:c.c1(1,.4,4096,4,1,32).schema}}),zo=h,de=class extends P{constructor(e){super(je,e);}};var Be="gemini-1.0-pro",en="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",De=ChatModelSchema(u,I).parse({name:Be,description:en,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:L,config:{def:c.base(1,.9,2048,4,1).def,schema:c.base(1,.9,2048,4,1).schema}}),jo=h,pe=class extends P{constructor(e){super(De,e);}};var Ue="gemini-1.0-pro-001",tn="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",Ae=ChatModelSchema(u,I).parse({name:Ue,description:tn,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:L,config:{def:c.base(1,.9,2048,4,1).def,schema:c.base(1,.9,2048,4,1).schema}}),Bo=h,ce=class extends P{constructor(e){super(Ae,e);}};var Ve="gemini-1.0-pro-latest",sn="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",He=ChatModelSchema(u,I).parse({name:Ve,description:sn,maxInputTokens:30720,maxOutputTokens:2048,roles:y,modalities:L,config:{def:c.base(1,.9,2048,4,1).def,schema:c.base(1,.9,2048,4,1).schema}}),Do=h,fe=class extends P{constructor(e){super(He,e);}};var Ke="gemini-1.0-pro-vision",rn="Google's predecessor to Gemini 1.5 Pro, an image understanding model to handle a broad range of applications",Ye=ChatModelSchema(u,re).parse({name:Ke,description:rn,maxInputTokens:12288,maxOutputTokens:4096,roles:y,modalities:ae,config:{def:c.c1(1,.4,4096,4,1,32).def,schema:c.c1(1,.4,4096,4,1,32).schema}}),Uo=h,he=class extends P{constructor(e){super(Ye,e);}};var Je="gemini-1.5-flash",mn="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(u,E).parse({name:Je,description:mn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,64).def,schema:c.c1(2,1,8192,4,.95,64).schema}}),Ao=h,ge=class extends T{constructor(e){super(We,e);}};var Xe="gemini-1.5-flash-001",pn="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",Qe=ChatModelSchema(u,E).parse({name:Xe,description:pn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,64).def,schema:c.c1(2,1,8192,4,.95,64).schema}}),Vo=h,ue=class extends T{constructor(e){super(Qe,e);}};var Ze="gemini-1.5-flash-002",fn="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(u,E).parse({name:Ze,description:fn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,40).def,schema:c.c1(2,1,8192,4,.95,40).schema}}),Ho=h,ye=class extends T{constructor(e){super(eo,e);}};var oo="gemini-1.5-flash-latest",gn="Google's latest multimodal model with great performance for high-frequency tasks. Optimized for fast and versatile performance across a diverse variety of tasks",to=ChatModelSchema(u,E).parse({name:oo,description:gn,maxInputTokens:1e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,64).def,schema:c.c1(2,1,8192,4,.95,64).schema}}),Ko=h,Ce=class extends T{constructor(e){super(to,e);}};var no="gemini-1.5-pro",yn="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",so=ChatModelSchema(u,E).parse({name:no,description:yn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,64).def,schema:c.c1(2,1,8192,4,.95,64).schema}}),Yo=h,Te=class extends T{constructor(e){super(so,e);}};var io="gemini-1.5-pro-001",Tn="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(u,E).parse({name:io,description:Tn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,64).def,schema:c.c1(2,1,8192,4,.95,64).schema}}),Jo=h,Ge=class extends T{constructor(e){super(ao,e);}};var ro="gemini-1.5-pro-002",Mn="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(u,E).parse({name:ro,description:Mn,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,40).def,schema:c.c1(2,1,8192,4,.95,40).schema}}),Wo=h,Me=class extends T{constructor(e){super(lo,e);}};var mo="gemini-1.5-pro-latest",_n="Google's best performing multimodal model with features for a wide variety of reasoning tasks. Optimized for complex reasoning tasks requiring more intelligence",po=ChatModelSchema(u,E).parse({name:mo,description:_n,maxInputTokens:2e6,maxOutputTokens:8192,roles:y,modalities:_,config:{def:c.c1(2,1,8192,4,.95,64).def,schema:c.c1(2,1,8192,4,.95,64).schema}}),Xo=h,be=class extends T{constructor(e){super(po,e);}};var Re=[EmbeddingTextModalityLiteral],xe=z$1.enum([EmbeddingTextModalityLiteral]);var it=z$1.object({embeddings:z$1.array(z$1.object({values:z$1.array(z$1.number())}))});var On=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)})}),at=z$1.object({model:z$1.string().min(1).optional(),requests:z$1.array(On).min(1),outputDimensionality:z$1.number().int().min(1).optional()});var ee=z$1.object({modelName:z$1.string(),apiKey:z$1.string(),baseUrl:z$1.string().url(),getEmbeddingsUrl:z$1.string().url().optional()}),A=class{constructor(e,o){this.version="v1";let t=ee.parse(o);this.modelSchema=e,this.modelName=t.modelName,this.apiKey=t.apiKey,this.baseUrl=urlWithoutTrailingSlash(t.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",source:"adaline.ai"}}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=at.safeParse(e);if(!o.success)throw new InvalidModelRequestError({info:"Invalid model request",cause:o.error});let t=o.data,s=t.model,r={outputDimensionality:t.outputDimensionality},n=Config().parse(removeUndefinedEntries(r)),m={modality:EmbeddingTextModalityLiteral,requests:t.requests.reduce((l,p)=>(l.push(...p.content.parts.map(f=>f.text)),l),[])};return {modelName:s,config:n,embeddingRequests:m}}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(n=>{if(!this.modelSchema.config.def[n])throw new InvalidConfigError({info:`Invalid config for model : '${this.modelName}'`,cause:new Error(`Invalid config key : '${n}',
|
|
13
|
+
available keys : [${Object.keys(this.modelSchema.config.def).join(", ")}]`)})}),Object.keys(s).reduce((n,m)=>{let p=this.modelSchema.config.def[m].param,f=s[m];return n[p]=f,n},{})}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(s=>({model:`models/${this.modelName}`,content:{parts:[{text:s}]}}))}}getGetEmbeddingsUrl(e,o){return R(this,null,function*(){return new Promise(t=>{t(this.getEmbeddingsUrl);})})}getGetEmbeddingsHeaders(e,o){return R(this,null,function*(){return new Promise(t=>{t(this.getDefaultHeaders());})})}getGetEmbeddingsData(e,o){return R(this,null,function*(){return new Promise(t=>{let s=this.transformConfig(e),r=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")});s.outputDimensionality&&(r.requests.forEach(n=>{n.outputDimensionality=s.outputDimensionality;}),delete s.outputDimensionality),t(G(G(G({},this.getDefaultParams()),s),r));})})}transformGetEmbeddingsResponse(e){let o=it.safeParse(e);if(o.success){let s=o.data.embeddings.map((r,n)=>({index:n,embedding:r.values}));return {encodingFormat:FloatEmbeddingLiteral,embeddings:s}}throw new ModelResponseError({info:"Invalid response from model",cause:o.error})}};var co="text-embedding-001",kn="text-embedding-001",fo=EmbeddingModelSchema(xe).parse({name:co,description:kn,modalities:Re,maxInputTokens:2048,maxOutputTokens:768,config:{def:j.base(768).def,schema:j.base(768).schema}}),Qo=ee,_e=class extends A{constructor(e){super(fo,e);}};var ho="text-embedding-004",vn="text-embedding-004",go=EmbeddingModelSchema(xe).parse({name:ho,description:vn,modalities:Re,maxInputTokens:2048,maxOutputTokens:768,config:{def:j.base(768).def,schema:j.base(768).schema}}),Zo=ee,Ee=class extends A{constructor(e){super(go,e);}};
|
|
16
14
|
|
|
17
|
-
export {
|
|
15
|
+
export { T as BaseChatModel, P as BaseChatModelGemini1, h as BaseChatModelOptions, A as BaseEmbeddingModel, ee as BaseEmbeddingModelOptions, Eo as ChatModelBaseConfigDef, _o as ChatModelBaseConfigSchema, Po as ChatModelC1ConfigDef, Oo as ChatModelC1ConfigSchema, xo as EmbeddingModelBaseConfigDef, Ro as EmbeddingModelBaseConfigSchema, pe as Gemini1_0Pro, fe as Gemini1_0ProLatest, Ve as Gemini1_0ProLatestLiteral, Do as Gemini1_0ProLatestOptions, He as Gemini1_0ProLatestSchema, Be as Gemini1_0ProLiteral, jo as Gemini1_0ProOptions, De as Gemini1_0ProSchema, he as Gemini1_0ProVision, Ke as Gemini1_0ProVisionLiteral, Uo as Gemini1_0ProVisionOptions, Ye as Gemini1_0ProVisionSchema, ce as Gemini1_0Pro_001, Ue as Gemini1_0Pro_001Literal, Bo as Gemini1_0Pro_001Options, Ae as Gemini1_0Pro_001Schema, ge as Gemini1_5Flash, ue as Gemini1_5Flash001, Xe as Gemini1_5Flash001Literal, Vo as Gemini1_5Flash001Options, Qe as Gemini1_5Flash001Schema, ye as Gemini1_5Flash002, Ze as Gemini1_5Flash002Literal, Ho as Gemini1_5Flash002Options, eo as Gemini1_5Flash002Schema, Ce as Gemini1_5FlashLatest, oo as Gemini1_5FlashLatestLiteral, Ko as Gemini1_5FlashLatestOptions, to as Gemini1_5FlashLatestSchema, Je as Gemini1_5FlashLiteral, Ao as Gemini1_5FlashOptions, We as Gemini1_5FlashSchema, Te as Gemini1_5Pro, Ge as Gemini1_5Pro001, io as Gemini1_5Pro001Literal, Jo as Gemini1_5Pro001Options, ao as Gemini1_5Pro001Schema, Me as Gemini1_5Pro002, ro as Gemini1_5Pro002Literal, Wo as Gemini1_5Pro002Options, lo as Gemini1_5Pro002Schema, be as Gemini1_5ProLatest, mo as Gemini1_5ProLatestLiteral, Xo as Gemini1_5ProLatestOptions, po as Gemini1_5ProLatestSchema, no as Gemini1_5ProLiteral, Yo as Gemini1_5ProOptions, so as Gemini1_5ProSchema, me as GeminiPro, Fe as GeminiProLiteral, $o as GeminiProOptions, $e as GeminiProSchema, de as GeminiProVision, ze as GeminiProVisionLiteral, zo as GeminiProVisionOptions, je as GeminiProVisionSchema, Y as Google, St as GoogleChatAssistantRoleLiteral, qt as GoogleChatContent, Nt as GoogleChatContentPartFunctionCall, vt as GoogleChatContentPartFunctionResponse, kt as GoogleChatContentPartInlineData, qo as GoogleChatContentPartText, No as GoogleChatGenerationConfig, c as GoogleChatModelConfigs, _ as GoogleChatModelModalities, E as GoogleChatModelModalitiesEnum, u as GoogleChatModelRoles, y as GoogleChatModelRolesMap, is as GoogleChatModelTextModalities, as as GoogleChatModelTextModalitiesEnum, L as GoogleChatModelTextToolModalities, I as GoogleChatModelTextToolModalitiesEnum, ae as GoogleChatModelTextVisionModalities, re as GoogleChatModelTextVisionModalitiesEnum, Fo as GoogleChatRequest, Io as GoogleChatSystemInstruction, Ft as GoogleChatTool, ko as GoogleChatToolConfig, Rt as GoogleChatToolRoleLiteral, wo as GoogleCompleteChatResponse, xt as GoogleCompleteChatTextResponse, wt as GoogleCompleteChatToolResponse, j as GoogleEmbeddingModelConfigs, Re as GoogleEmbeddingModelModalities, xe as GoogleEmbeddingModelModalitiesEnum, at as GoogleEmbeddingRequest, On as GoogleEmbeddingRequestInput, it as GoogleGetEmbeddingsResponse, Lo as GoogleStreamChatResponse, Lt as GoogleStreamChatTextResponse, It as GoogleStreamChatToolResponse, $t as ProviderLiteral, _e as Text_Embedding_001, co as Text_Embedding_001Literal, Qo as Text_Embedding_001Options, fo as Text_Embedding_001Schema, Ee as Text_Embedding_004, ho as Text_Embedding_004Literal, Zo as Text_Embedding_004Options, go as Text_Embedding_004Schema, ve as dimensions, Ie as frequencyPenalty, v as maxTokens, ke as presencePenalty, z as safetySettings, Ne as seed, q as stop, N as temperature, $ as toolChoice, Le as topK, F as topP };
|
|
18
16
|
//# sourceMappingURL=index.mjs.map
|
|
19
17
|
//# sourceMappingURL=index.mjs.map
|