UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

6 lines (4 loc) 103 kB
import{AISDKError as e,TooManyEmbeddingValuesForCallError as t,UnsupportedFunctionalityError as n}from"../provider/index.js";import{At as r,Et as i,Nn as a,Rn as o,Tn as s,Xn as c,Zn as l,dn as u,wn as d,yt as f}from"../../_chunks/workflow/schemas-iG9Z4s4o.js";import{A as p,B as m,C as h,E as g,G as _,H as v,J as y,L as b,N as x,O as S,P as C,Q as w,S as ee,T as te,U as T,V as E,X as D,Y as ne,Z as O,_ as k,a as re,b as A,c as ie,d as ae,f as j,h as M,i as oe,j as se,o as N,r as P,u as F,w as I,x as L,z as R}from"../../_chunks/workflow/dist-DTchiX0N.js";var ce=`4.0.0-beta.82`,z=ae({errorSchema:p(()=>D(s({error:s({code:d().nullable(),message:o(),status:o()})}))),errorToMessage:e=>e.error.message}),le=c([s({text:o()}),s({inlineData:s({mimeType:o(),data:o()})}),s({fileData:s({fileUri:o(),mimeType:o()})})]),ue=p(()=>D(s({outputDimensionality:d().optional(),taskType:f([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional(),content:i(i(le).min(1).nullable()).optional()}))),de=class e{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[w](e){return _({modelId:e.modelId,config:e.config})}static[O](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async doEmbed({values:e,headers:n,abortSignal:r,providerOptions:i}){let a=await b({provider:`google`,providerOptions:i,schema:ue});if(e.length>this.maxEmbeddingsPerCall)throw new t({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=P(this.config.headers?await m(this.config.headers):void 0,n),s=a?.content;if(s!=null&&s.length!==e.length)throw Error(`The number of multimodal content entries (${s.length}) must match the number of values (${e.length}).`);if(e.length===1){let t=s?.[0],n=e[0]?[{text:e[0]}]:[],i=t==null?[{text:e[0]}]:[...n,...t],{responseHeaders:c,value:l,rawValue:u}=await R({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:o,body:{model:`models/${this.modelId}`,content:{parts:i},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType},failedResponseHandler:z,successfulResponseHandler:j(pe),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:[l.embedding.values],usage:void 0,response:{headers:c,body:u}}}let{responseHeaders:c,value:l,rawValue:u}=await R({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:o,body:{requests:e.map((e,t)=>{let n=s?.[t],r=e?[{text:e}]:[];return{model:`models/${this.modelId}`,content:{role:`user`,parts:n==null?[{text:e}]:[...r,...n]},outputDimensionality:a?.outputDimensionality,taskType:a?.taskType}})},failedResponseHandler:z,successfulResponseHandler:j(fe),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.embeddings.map(e=>e.values),usage:void 0,response:{headers:c,body:u}}}},fe=p(()=>D(s({embeddings:i(s({values:i(d())}))}))),pe=p(()=>D(s({embedding:s({values:i(d())})})));function me(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.promptTokenCount??0,n=e.candidatesTokenCount??0,r=e.cachedContentTokenCount??0,i=e.thoughtsTokenCount??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n+i,text:n,reasoning:i},raw:e}}function B(e,t=!0){if(e==null)return;if(he(e))return t?void 0:typeof e==`object`&&e.description?{type:`object`,description:e.description}:{type:`object`};if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:n,description:r,required:i,properties:a,items:o,allOf:s,anyOf:c,oneOf:l,format:u,const:d,minLength:f,enum:p}=e,m={};if(r&&(m.description=r),i&&(m.required=i),u&&(m.format=u),d!==void 0&&(m.enum=[d]),n)if(Array.isArray(n)){let e=n.includes(`null`),t=n.filter(e=>e!==`null`);t.length===0?m.type=`null`:(m.anyOf=t.map(e=>({type:e})),e&&(m.nullable=!0))}else m.type=n;if(p!==void 0&&(m.enum=p),a!=null&&(m.properties=Object.entries(a).reduce((e,[t,n])=>(e[t]=B(n,!1),e),{})),o&&(m.items=Array.isArray(o)?o.map(e=>B(e,!1)):B(o,!1)),s&&(m.allOf=s.map(e=>B(e,!1))),c)if(c.some(e=>typeof e==`object`&&e?.type===`null`)){let e=c.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=B(e[0],!1);typeof t==`object`&&(m.nullable=!0,Object.assign(m,t))}else m.anyOf=e.map(e=>B(e,!1)),m.nullable=!0}else m.anyOf=c.map(e=>B(e,!1));return l&&(m.oneOf=l.map(e=>B(e,!1))),f!==void 0&&(m.minLength=f),m}function he(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}var ge=`skip_thought_signature_validator`,_e=/^data:([^;,]+);base64,(.+)$/s;function ve(e){let t=_e.exec(e);if(t!=null)return{mediaType:t[1],data:t[2]}}function ye(e){let t=ve(e);if(t!=null)return{inlineData:{mimeType:t.mediaType,data:t.data}}}function be(e,t,n,r){let i=[],a=[];for(let e of n)switch(e.type){case`text`:a.push(e.text);break;case`file`:if(e.data.type===`data`)i.push({inlineData:{mimeType:E({part:e}),data:N(e.data.data)}});else if(e.data.type===`url`){let t=ye(e.data.url.toString());t==null?a.push(JSON.stringify(e)):i.push(t)}else a.push(JSON.stringify(e));break;default:a.push(JSON.stringify(e));break}e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:a.length>0?a.join(` `):`Tool executed successfully.`},...i.length>0?{parts:i}:{}}})}function xe(e,t,n,r){for(let i of n)switch(i.type){case`text`:e.push({functionResponse:{...r==null?{}:{id:r},name:t,response:{name:t,content:i.text}}});break;case`file`:i.data.type===`data`&&h(i.mediaType)===`image`?e.push({inlineData:{mimeType:E({part:i}),data:N(i.data.data)}},{text:`Tool executed successfully and returned this image as a response`}):e.push({text:JSON.stringify(i)});break;default:e.push({text:JSON.stringify(i)});break}}function Se(e,t){let r=[],i=[],a=!0,o=t?.isGemmaModel??!1,s=t?.isGemini3Model??!1,c=t?.onWarning,l=t?.providerOptionsNames??[`google`],u=!l.includes(`google`),d=t?.supportsFunctionResponseParts??!0,f=!1,p=[],m=e=>(p.push(e),f=!0,ge),h=e=>{for(let t of l){let n=e.providerOptions?.[t];if(n!=null)return n}return u?e.providerOptions?.google:e.providerOptions?.googleVertex??e.providerOptions?.vertex};for(let{role:t,content:o}of e)switch(t){case`system`:if(!a)throw new n({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:o});break;case`user`:{a=!1;let e=[];for(let t of o)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:switch(t.data.type){case`url`:e.push({fileData:{mimeType:E({part:t}),fileUri:t.data.url.toString()}});break;case`reference`:if(u)throw new n({functionality:`file parts with provider references`});e.push({fileData:{mimeType:E({part:t}),fileUri:v({reference:t.data.reference,provider:`google`})}});break;case`text`:e.push({inlineData:{mimeType:g(t.mediaType)?t.mediaType:`text/plain`,data:N(new TextEncoder().encode(t.data.text))}});break;case`data`:e.push({inlineData:{mimeType:E({part:t}),data:N(t.data.data)}});break}break}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:o.map(e=>{let t=h(e),r=t?.thoughtSignature==null?void 0:String(t.thoughtSignature);switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:r};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:r};case`reasoning-file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`data`:return{inlineData:{mimeType:e.mediaType,data:N(e.data.data)},thought:!0,thoughtSignature:r}}break;case`file`:switch(e.data.type){case`url`:throw new n({functionality:`File data URLs in assistant messages are not supported`});case`reference`:if(u)throw new n({functionality:`file parts with provider references`});return{fileData:{mimeType:e.mediaType,fileUri:v({reference:e.data.reference,provider:`google`})},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`text`:return{inlineData:{mimeType:g(e.mediaType)?e.mediaType:`text/plain`,data:N(new TextEncoder().encode(e.data.text))},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r};case`data`:return{inlineData:{mimeType:e.mediaType,data:N(e.data.data)},...t?.thought===!0?{thought:!0}:{},thoughtSignature:r}}break;case`tool-call`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType),a=r??(s?m(e.toolName):void 0);return n&&i?{toolCall:{toolType:i,args:typeof e.input==`string`?JSON.parse(e.input):e.input,id:n},thoughtSignature:a}:{functionCall:{...e.toolCallId==null?{}:{id:e.toolCallId},name:e.toolName,args:e.input},thoughtSignature:a}}case`tool-result`:{let n=t?.serverToolCallId==null?void 0:String(t.serverToolCallId),i=t?.serverToolType==null?void 0:String(t.serverToolType);return n&&i?{toolResponse:{toolType:i,response:e.output.type===`json`?e.output.value:{},id:n},thoughtSignature:r}:void 0}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of o){if(t.type===`tool-approval-response`)continue;let n=h(t),r=n?.serverToolCallId==null?void 0:String(n.serverToolCallId),a=n?.serverToolType==null?void 0:String(n.serverToolType);if(r&&a){let e=n?.thoughtSignature==null?void 0:String(n.thoughtSignature);if(i.length>0){let n=i[i.length-1];if(n.role===`model`){n.parts.push({toolResponse:{toolType:a,response:t.output.type===`json`?t.output.value:{},id:r},thoughtSignature:e});continue}}}let o=t.output;o.type===`content`?d?be(e,t.toolName,o.value,t.toolCallId):xe(e,t.toolName,o.value,t.toolCallId):e.push({functionResponse:{...t.toolCallId==null?{}:{id:t.toolCallId},name:t.toolName,response:{name:t.toolName,content:o.type===`execution-denied`?o.reason??`Tool call execution denied.`:o.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(` `);i[0].parts.unshift({text:e+` `})}if(f&&c!=null){let e=Array.from(new Set(p));c({type:`other`,message:`Replayed ${p.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${e.map(e=>`\`${e}\``).join(`, `)}). Injected the documented \`skip_thought_signature_validator\` sentinel to keep the request from failing with HTTP 400. The likely cause is application code that drops \`providerOptions.google.thoughtSignature\` when persisting or serializing assistant tool-call messages. See https://ai.google.dev/gemini-api/docs/thought-signatures.`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function V(e){return e.includes(`/`)?e:`models/${e}`}var Ce=p(()=>D(s({responseModalities:i(f([`TEXT`,`IMAGE`])).optional(),thinkingConfig:s({thinkingBudget:d().optional(),includeThoughts:r().optional(),thinkingLevel:f([`minimal`,`low`,`medium`,`high`]).optional()}).optional(),cachedContent:o().optional(),structuredOutputs:r().optional(),safetySettings:i(s({category:f([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:f([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:r().optional(),labels:a(o(),o()).optional(),mediaResolution:f([`MEDIA_RESOLUTION_UNSPECIFIED`,`MEDIA_RESOLUTION_LOW`,`MEDIA_RESOLUTION_MEDIUM`,`MEDIA_RESOLUTION_HIGH`]).optional(),imageConfig:s({aspectRatio:f([`1:1`,`2:3`,`3:2`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`,`1:8`,`8:1`,`1:4`,`4:1`]).optional(),imageSize:f([`1K`,`2K`,`4K`,`512`]).optional()}).optional(),retrievalConfig:s({latLng:s({latitude:d(),longitude:d()}).optional()}).optional(),streamFunctionCallArguments:r().optional(),serviceTier:f([`standard`,`flex`,`priority`]).optional(),sharedRequestType:f([`priority`,`flex`,`standard`]).optional(),requestType:f([`shared`]).optional()})));function we({tools:e,toolChoice:t,modelId:r,isVertexProvider:i=!1}){e=e?.length?e:void 0;let a=[],o=[`gemini-flash-latest`,`gemini-flash-lite-latest`,`gemini-pro-latest`].some(e=>e===r),s=r.includes(`gemini-2`)||r.includes(`gemini-3`)||r.includes(`nano-banana`)||o,c=r.includes(`gemini-3`),l=r.includes(`gemini-2.5`)||r.includes(`gemini-3`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:a};let u=e.some(e=>e.type===`function`),d=e.some(e=>e.type===`provider`);if(u&&d&&!c&&a.push({type:`unsupported`,feature:`combination of function and provider-defined tools`}),d){let n=[];if(e.filter(e=>e.type===`provider`).forEach(e=>{switch(e.id){case`google.google_search`:s?n.push({googleSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Google Search requires Gemini 2.0 or newer.`});break;case`google.enterprise_web_search`:s?n.push({enterpriseWebSearch:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`Enterprise Web Search requires Gemini 2.0 or newer.`});break;case`google.url_context`:s?n.push({urlContext:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:s?n.push({codeExecution:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The code execution tool is not supported with other Gemini models than Gemini 2.`});break;case`google.file_search`:l?n.push({fileSearch:{...e.args}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The file search tool is only supported with Gemini 2.5 models and Gemini 3 models.`});break;case`google.vertex_rag_store`:s?n.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:e.args.ragCorpus},similarity_top_k:e.args.topK}}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The RAG store tool is not supported with other Gemini models than Gemini 2.`});break;case`google.google_maps`:s?n.push({googleMaps:{}}):a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`,details:`The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer.`});break;default:a.push({type:`unsupported`,feature:`provider-defined tool ${e.id}`});break}}),u&&c&&n.length>0){let r=[];for(let t of e)t.type===`function`&&r.push({name:t.name,description:t.description??``,parameters:B(t.inputSchema)});let o={functionCallingConfig:{mode:`VALIDATED`},...!i&&{includeServerSideToolInvocations:!0}};if(t!=null)switch(t.type){case`auto`:break;case`none`:o.functionCallingConfig={mode:`NONE`};break;case`required`:o.functionCallingConfig={mode:`ANY`};break;case`tool`:o.functionCallingConfig={mode:`ANY`,allowedFunctionNames:[t.toolName]};break}return{tools:[...n,{functionDeclarations:r}],toolConfig:o,toolWarnings:a}}return{tools:n.length>0?n:void 0,toolConfig:void 0,toolWarnings:a}}let f=[],p=!1;for(let t of e)switch(t.type){case`function`:f.push({name:t.name,description:t.description??``,parameters:B(t.inputSchema)}),t.strict===!0&&(p=!0);break;default:a.push({type:`unsupported`,feature:`function tool ${t.name}`});break}if(t==null)return{tools:[{functionDeclarations:f}],toolConfig:p?{functionCallingConfig:{mode:`VALIDATED`}}:void 0,toolWarnings:a};let m=t.type;switch(m){case`auto`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`AUTO`}},toolWarnings:a};case`none`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:a};case`required`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`}},toolWarnings:a};case`tool`:return{tools:[{functionDeclarations:f}],toolConfig:{functionCallingConfig:{mode:p?`VALIDATED`:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:a};default:throw new n({functionality:`tool choice type: ${m}`})}}var Te=class{constructor(){this.accumulatedArgs={},this.jsonText=``,this.pathStack=[],this.stringOpen=!1}processPartialArgs(e){let t=``;for(let n of e){let e=n.jsonPath.replace(/^\$\./,``);if(!e)continue;let r=Ee(e),i=Ae(this.accumulatedArgs,r);if(n.stringValue!=null&&i!==void 0){let e=JSON.stringify(n.stringValue).slice(1,-1);je(this.accumulatedArgs,r,i+n.stringValue),t+=e;continue}let a=Me(n);a!=null&&(je(this.accumulatedArgs,r,a.value),t+=this.emitNavigationTo(r,n,a.json))}return this.jsonText+=t,{currentJSON:this.accumulatedArgs,textDelta:t}}finalize(){let e=JSON.stringify(this.accumulatedArgs);return{finalJSON:e,closingDelta:e.slice(this.jsonText.length)}}ensureRoot(){return this.pathStack.length===0?(this.pathStack.push({segment:``,isArray:!1,childCount:0}),`{`):``}emitNavigationTo(e,t,n){let r=``;this.stringOpen&&=(r+=`"`,!1),r+=this.ensureRoot();let i=e.slice(0,-1),a=e[e.length-1],o=this.findCommonStackDepth(i);return r+=this.closeDownTo(o),r+=this.openDownTo(i,a),r+=this.emitLeaf(a,t,n),r}findCommonStackDepth(e){let t=Math.min(this.pathStack.length-1,e.length),n=0;for(let r=0;r<t&&this.pathStack[r+1].segment===e[r];r++)n++;return n+1}closeDownTo(e){let t=``;for(;this.pathStack.length>e;){let e=this.pathStack.pop();t+=e.isArray?`]`:`}`}return t}openDownTo(e,t){let n=``,r=this.pathStack.length-1;for(let i=r;i<e.length;i++){let r=e[i],a=this.pathStack[this.pathStack.length-1];a.childCount>0&&(n+=`,`),a.childCount++,typeof r==`string`&&(n+=`${JSON.stringify(r)}:`);let o=typeof(i+1<e.length?e[i+1]:t)==`number`;n+=o?`[`:`{`,this.pathStack.push({segment:r,isArray:o,childCount:0})}return n}emitLeaf(e,t,n){let r=``,i=this.pathStack[this.pathStack.length-1];return i.childCount>0&&(r+=`,`),i.childCount++,typeof e==`string`&&(r+=`${JSON.stringify(e)}:`),t.stringValue!=null&&t.willContinue?(r+=n.slice(0,-1),this.stringOpen=!0):r+=n,r}};function Ee(e){let t=[];for(let n of e.split(`.`)){let e=n.indexOf(`[`);if(e===-1)t.push(n);else{e>0&&t.push(n.slice(0,e));for(let e of n.matchAll(/\[(\d+)\]/g))t.push(parseInt(e[1],10))}}return t}var De=Object.prototype.hasOwnProperty;function Oe(e,t){return De.call(e,t)}function ke(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function Ae(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;let t=n;if(!Oe(t,e))return;n=t[e]}return n}function je(e,t,n){let r=e;for(let e=0;e<t.length-1;e++){let n=t[e],i=t[e+1];(!Oe(r,n)||r[n]==null)&&ke(r,n,typeof i==`number`?[]:{}),r=r[n]}ke(r,t[t.length-1],n)}function Me(e){let t=e.stringValue??e.numberValue??e.boolValue;if(t!=null)return{value:t,json:JSON.stringify(t)};if(`nullValue`in e)return{value:null,json:`null`}}function Ne({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`other`}}var Pe=class e{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.config=t,this.generateId=t.generateId??A}static[w](e){return _({modelId:e.modelId,config:e.config})}static[O](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,reasoning:f,providerOptions:p},{isStreaming:m=!1}={}){let h=[],g=this.config.provider.includes(`vertex`)?[`googleVertex`,`vertex`]:[`google`],_;for(let e of g)if(_=await b({provider:e,providerOptions:p,schema:Ce}),_!=null)break;_==null&&!g.includes(`google`)&&(_=await b({provider:`google`,providerOptions:p,schema:Ce}));let v=this.config.provider.startsWith(`google.vertex.`);u?.some(e=>e.type===`provider`&&e.id===`google.vertex_rag_store`)&&!v&&h.push({type:`other`,message:`The 'vertex_rag_store' tool is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`}),_?.streamFunctionCallArguments&&!v&&h.push({type:`other`,message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${this.config.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`}),_?.serviceTier&&v&&h.push({type:`other`,message:`'serviceTier' is a Gemini API option and is not supported on Vertex AI. Use 'sharedRequestType' (and optionally 'requestType') instead. See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/priority-paygo`}),(_?.sharedRequestType||_?.requestType)&&!v&&h.push({type:`other`,message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${this.config.provider}).`});let y=v&&(_?.sharedRequestType||_?.requestType)?{..._.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":_.sharedRequestType},..._.requestType&&{"X-Vertex-AI-LLM-Request-Type":_.requestType}}:void 0,x=v?void 0:_?.serviceTier,S=this.modelId.toLowerCase().startsWith(`gemma-`),C=/^gemini-3[.-]/.test(this.modelId),{contents:w,systemInstruction:ee}=Se(e,{isGemmaModel:S,isGemini3Model:C,onWarning:e=>h.push(e),providerOptionsNames:g,supportsFunctionResponseParts:C}),{tools:te,toolConfig:T,toolWarnings:E}=we({tools:u,toolChoice:d,modelId:this.modelId,isVertexProvider:v}),D=Re({reasoning:f,modelId:this.modelId,warnings:h}),ne=_?.thinkingConfig||D?{...D,..._?.thinkingConfig}:void 0,O=m&&v?_?.streamFunctionCallArguments??!1:void 0,k=T||O||_?.retrievalConfig?{...T,...O&&{functionCallingConfig:{...T?.functionCallingConfig,streamFunctionCallArguments:!0}},..._?.retrievalConfig&&{retrievalConfig:_.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&(_?.structuredOutputs??!0)?B(c.schema):void 0,..._?.audioTimestamp&&{audioTimestamp:_.audioTimestamp},responseModalities:_?.responseModalities,thinkingConfig:ne,..._?.mediaResolution&&{mediaResolution:_.mediaResolution},..._?.imageConfig&&{imageConfig:_.imageConfig}},contents:w,systemInstruction:S?void 0:ee,safetySettings:_?.safetySettings,tools:te,toolConfig:k,cachedContent:_?.cachedContent,labels:_?.labels,serviceTier:x},warnings:[...h,...E],providerOptionsNames:g,extraHeaders:y}}async doGenerate(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=P(this.config.headers?await m(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c,rawValue:l}=await R({url:`${this.config.baseURL}/${V(this.modelId)}:generateContent`,headers:o,body:t,failedResponseHandler:z,successfulResponseHandler:j(Je),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=c.candidates[0],d=[],f=u.content?.parts??[],p=c.usageMetadata,h,g;for(let e of f)if(`executableCode`in e&&e.executableCode?.code){let t=this.config.generateId();h=t,d.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in e&&e.codeExecutionResult)d.push({type:`tool-result`,toolCallId:h,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output??``}}),h=void 0;else if(`text`in e&&e.text!=null){let t=e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0;if(e.text.length===0){if(t!=null&&d.length>0){let e=d[d.length-1];e.providerMetadata=t}}else d.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:t})}else if(`functionCall`in e&&e.functionCall.name!=null)d.push({type:`tool-call`,toolCallId:e.functionCall.id??this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args??{}),providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature}):void 0});else if(`inlineData`in e){let t=e.thought===!0,n=!!e.thoughtSignature;d.push({type:t?`reasoning-file`:`file`,data:{type:`data`,data:e.inlineData.data},mediaType:e.inlineData.mimeType,providerMetadata:n?a({thoughtSignature:e.thoughtSignature}):void 0})}else if(`toolCall`in e&&e.toolCall){let t=e.toolCall.id??this.config.generateId();g=t,d.push({type:`tool-call`,toolCallId:t,toolName:`server:${e.toolCall.toolType}`,input:JSON.stringify(e.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolCall.toolType}):a({serverToolCallId:t,serverToolType:e.toolCall.toolType})})}else if(`toolResponse`in e&&e.toolResponse){let t=g??e.toolResponse.id??this.config.generateId();d.push({type:`tool-result`,toolCallId:t,toolName:`server:${e.toolResponse.toolType}`,result:e.toolResponse.response??{},providerMetadata:e.thoughtSignature?a({thoughtSignature:e.thoughtSignature,serverToolCallId:t,serverToolType:e.toolResponse.toolType}):a({serverToolCallId:t,serverToolType:e.toolResponse.toolType})}),g=void 0}let _=Ve({groundingMetadata:u.groundingMetadata,generateId:this.config.generateId})??[];for(let e of _)d.push(e);return{content:d,finishReason:{unified:Ne({finishReason:u.finishReason,hasToolCalls:d.some(e=>e.type===`tool-call`&&!e.providerExecuted)}),raw:u.finishReason??void 0},usage:me(p),warnings:n,providerMetadata:a({promptFeedback:c.promptFeedback??null,groundingMetadata:u.groundingMetadata??null,urlContextMetadata:u.urlContextMetadata??null,safetyRatings:u.safetyRatings??null,usageMetadata:p??null,finishMessage:u.finishMessage??null,serviceTier:p?.serviceTier??null}),request:{body:t},response:{headers:s,body:l}}}async doStream(e){let{args:t,warnings:n,providerOptionsNames:r,extraHeaders:i}=await this.getArgs(e,{isStreaming:!0}),a=e=>Object.fromEntries(r.map(t=>[t,e])),o=P(this.config.headers?await m(this.config.headers):void 0,e.headers,i),{responseHeaders:s,value:c}=await R({url:`${this.config.baseURL}/${V(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:t,failedResponseHandler:z,successfulResponseHandler:F(Ye),abortSignal:e.abortSignal,fetch:this.config.fetch}),l={unified:`other`,raw:void 0},u,d,f=null,p=null,h=this.config.generateId,g=!1,_=null,v=null,y=0,b=new Set,x,S,C=[],w=e=>{let t=C.pop();if(t==null)return;let{finalJSON:n,closingDelta:r}=t.accumulator.finalize();r.length>0&&e.enqueue({type:`tool-input-delta`,id:t.toolCallId,delta:r,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-input-end`,id:t.toolCallId,providerMetadata:t.providerMetadata}),e.enqueue({type:`tool-call`,toolCallId:t.toolCallId,toolName:t.toolName,input:n,providerMetadata:t.providerMetadata}),g=!0};return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let r=t.value,i=r.usageMetadata;i!=null&&(u=i);let o=r.candidates?.[0];if(o==null)return;let s=o.content;o.groundingMetadata!=null&&(f=o.groundingMetadata),o.urlContextMetadata!=null&&(p=o.urlContextMetadata);let c=Ve({groundingMetadata:o.groundingMetadata,generateId:h});if(c!=null)for(let e of c)e.sourceType===`url`&&!b.has(e.url)&&(b.add(e.url),n.enqueue(e));if(s!=null){let e=s.parts??[];for(let t of e)if(`executableCode`in t&&t.executableCode?.code){let e=h();x=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0})}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=x;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output??``}}),x=void 0)}else if(`text`in t&&t.text!=null){let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;t.text.length===0?e!=null&&_!==null&&n.enqueue({type:`text-delta`,id:_,delta:``,providerMetadata:e}):t.thought===!0?(_!==null&&(n.enqueue({type:`text-end`,id:_}),_=null),v===null&&(v=String(y++),n.enqueue({type:`reasoning-start`,id:v,providerMetadata:e})),n.enqueue({type:`reasoning-delta`,id:v,delta:t.text,providerMetadata:e})):(v!==null&&(n.enqueue({type:`reasoning-end`,id:v}),v=null),_===null&&(_=String(y++),n.enqueue({type:`text-start`,id:_,providerMetadata:e})),n.enqueue({type:`text-delta`,id:_,delta:t.text,providerMetadata:e}))}else if(`inlineData`in t){_!==null&&(n.enqueue({type:`text-end`,id:_}),_=null),v!==null&&(n.enqueue({type:`reasoning-end`,id:v}),v=null);let e=t.thought===!0,r=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0;n.enqueue({type:e?`reasoning-file`:`file`,mediaType:t.inlineData.mimeType,data:{type:`data`,data:t.inlineData.data},providerMetadata:r})}else if(`toolCall`in t&&t.toolCall){let e=t.toolCall.id??h();S=e;let r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolCall.toolType});n.enqueue({type:`tool-call`,toolCallId:e,toolName:`server:${t.toolCall.toolType}`,input:JSON.stringify(t.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:r})}else if(`toolResponse`in t&&t.toolResponse){let e=S??t.toolResponse.id??h(),r=a({...t.thoughtSignature?{thoughtSignature:t.thoughtSignature}:{},serverToolCallId:e,serverToolType:t.toolResponse.toolType});n.enqueue({type:`tool-result`,toolCallId:e,toolName:`server:${t.toolResponse.toolType}`,result:t.toolResponse.response??{},providerMetadata:r}),S=void 0}for(let t of e){if(!(`functionCall`in t))continue;let e=t.thoughtSignature?a({thoughtSignature:t.thoughtSignature}):void 0,r=t.functionCall.partialArgs!=null||t.functionCall.name!=null&&t.functionCall.willContinue===!0,i=t.functionCall.name==null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue==null,o=t.functionCall.name!=null&&t.functionCall.args!=null&&t.functionCall.partialArgs==null,s=t.functionCall.name!=null&&t.functionCall.args==null&&t.functionCall.partialArgs==null&&t.functionCall.willContinue!==!0;if(r){if(t.functionCall.name!=null){let r=t.functionCall.id??h(),i=new Te;if(C.push({toolCallId:r,toolName:t.functionCall.name,accumulator:i,providerMetadata:e}),n.enqueue({type:`tool-input-start`,id:r,toolName:t.functionCall.name,providerMetadata:e}),t.functionCall.partialArgs!=null){let a=t.functionCall.partialArgs,{textDelta:o}=i.processPartialArgs(a);o.length>0&&n.enqueue({type:`tool-input-delta`,id:r,delta:o,providerMetadata:e}),t.functionCall.willContinue!==!0&&a.every(e=>e.willContinue!==!0)&&w(n)}}else if(t.functionCall.partialArgs!=null&&C.length>0){let r=C[C.length-1],i=t.functionCall.partialArgs,{textDelta:a}=r.accumulator.processPartialArgs(i);a.length>0&&n.enqueue({type:`tool-input-delta`,id:r.toolCallId,delta:a,providerMetadata:e}),t.functionCall.willContinue!==!0&&i.every(e=>e.willContinue!==!0)&&w(n)}}else if(i&&C.length>0)w(n);else if(o){let r=t.functionCall.id??h(),i=t.functionCall.name,a=typeof t.functionCall.args==`string`?t.functionCall.args:JSON.stringify(t.functionCall.args??{});n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-delta`,id:r,delta:a,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:a,providerMetadata:e}),g=!0}else if(s){let r=t.functionCall.id??h(),i=t.functionCall.name;n.enqueue({type:`tool-input-start`,id:r,toolName:i,providerMetadata:e}),n.enqueue({type:`tool-input-end`,id:r,providerMetadata:e}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:i,input:`{}`,providerMetadata:e}),g=!0}}}o.finishReason!=null&&(l={unified:Ne({finishReason:o.finishReason,hasToolCalls:g}),raw:o.finishReason},d=a({promptFeedback:r.promptFeedback??null,groundingMetadata:f,urlContextMetadata:p,safetyRatings:o.safetyRatings??null,usageMetadata:i??null,finishMessage:o.finishMessage??null,serviceTier:u?.serviceTier??null}))},flush(e){_!==null&&e.enqueue({type:`text-end`,id:_}),v!==null&&e.enqueue({type:`reasoning-end`,id:v}),e.enqueue({type:`finish`,finishReason:l,usage:me(u),providerMetadata:d})}})),response:{headers:s},request:{body:t}}}};function Fe(e){return/gemini-3[\.\-]/i.test(e)||/gemini-3$/i.test(e)}function Ie(){return 65536}function Le(e){let t=e.toLowerCase();return t.includes(`2.5-pro`)||t.includes(`gemini-3-pro-image`)?32768:24576}function Re({reasoning:e,modelId:t,warnings:n}){if(te(e))return Fe(t)&&!t.includes(`gemini-3-pro-image`)?ze({reasoning:e,warnings:n}):Be({reasoning:e,modelId:t,warnings:n})}function ze({reasoning:e,warnings:t}){if(e===`none`)return{thinkingLevel:`minimal`};let n=C({reasoning:e,effortMap:{minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`high`},warnings:t});if(n!=null)return{thinkingLevel:n}}function Be({reasoning:e,modelId:t,warnings:n}){if(e===`none`)return{thinkingBudget:0};let r=x({reasoning:e,maxOutputTokens:Ie(),maxReasoningBudget:Le(t),minReasoningBudget:0,warnings:n});if(r!=null)return{thinkingBudget:r}}function Ve({groundingMetadata:e,generateId:t}){if(!e?.groundingChunks)return;let n=[];for(let r of e.groundingChunks)if(r.web!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.web.uri,title:r.web.title??void 0});else if(r.image!=null)n.push({type:`source`,sourceType:`url`,id:t(),url:r.image.sourceUri,title:r.image.title??void 0});else if(r.retrievedContext!=null){let e=r.retrievedContext.uri,i=r.retrievedContext.fileSearchStore;if(e&&(e.startsWith(`http://`)||e.startsWith(`https://`)))n.push({type:`source`,sourceType:`url`,id:t(),url:e,title:r.retrievedContext.title??void 0});else if(e){let i=r.retrievedContext.title??`Unknown Document`,a=`application/octet-stream`,o;e.endsWith(`.pdf`)?(a=`application/pdf`,o=e.split(`/`).pop()):e.endsWith(`.txt`)?(a=`text/plain`,o=e.split(`/`).pop()):e.endsWith(`.docx`)?(a=`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,o=e.split(`/`).pop()):e.endsWith(`.doc`)?(a=`application/msword`,o=e.split(`/`).pop()):(e.match(/\.(md|markdown)$/)&&(a=`text/markdown`),o=e.split(`/`).pop()),n.push({type:`source`,sourceType:`document`,id:t(),mediaType:a,title:i,filename:o})}else if(i){let e=r.retrievedContext.title??`Unknown Document`;n.push({type:`source`,sourceType:`document`,id:t(),mediaType:`application/octet-stream`,title:e,filename:i.split(`/`).pop()})}}else r.maps!=null&&r.maps.uri&&n.push({type:`source`,sourceType:`url`,id:t(),url:r.maps.uri,title:r.maps.title??void 0});return n.length>0?n:void 0}var He=()=>s({webSearchQueries:i(o()).nullish(),imageSearchQueries:i(o()).nullish(),retrievalQueries:i(o()).nullish(),searchEntryPoint:s({renderedContent:o()}).nullish(),groundingChunks:i(s({web:s({uri:o(),title:o().nullish()}).nullish(),image:s({sourceUri:o(),imageUri:o(),title:o().nullish(),domain:o().nullish()}).nullish(),retrievedContext:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),fileSearchStore:o().nullish()}).nullish(),maps:s({uri:o().nullish(),title:o().nullish(),text:o().nullish(),placeId:o().nullish()}).nullish()})).nullish(),groundingSupports:i(s({segment:s({startIndex:d().nullish(),endIndex:d().nullish(),text:o().nullish()}).nullish(),segment_text:o().nullish(),groundingChunkIndices:i(d()).nullish(),supportChunkIndices:i(d()).nullish(),confidenceScores:i(d()).nullish(),confidenceScore:i(d()).nullish()})).nullish(),retrievalMetadata:c([s({webDynamicRetrievalScore:d()}),s({})]).nullish()}),Ue=s({jsonPath:o(),stringValue:o().nullish(),numberValue:d().nullish(),boolValue:r().nullish(),nullValue:l().nullish(),willContinue:r().nullish()}),We=()=>s({parts:i(c([s({functionCall:s({id:o().nullish(),name:o().nullish(),args:l().nullish(),partialArgs:i(Ue).nullish(),willContinue:r().nullish()}),thoughtSignature:o().nullish()}),s({inlineData:s({mimeType:o(),data:o()}),thought:r().nullish(),thoughtSignature:o().nullish()}),s({toolCall:s({toolType:o(),args:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({toolResponse:s({toolType:o(),response:l().nullish(),id:o()}),thoughtSignature:o().nullish()}),s({executableCode:s({language:o(),code:o()}).nullish(),codeExecutionResult:s({outcome:o(),output:o().nullish()}).nullish(),text:o().nullish(),thought:r().nullish(),thoughtSignature:o().nullish()})])).nullish()}),H=()=>s({category:o().nullish(),probability:o().nullish(),probabilityScore:d().nullish(),severity:o().nullish(),severityScore:d().nullish(),blocked:r().nullish()}),Ge=i(s({modality:o(),tokenCount:d()})).nullish(),Ke=s({cachedContentTokenCount:d().nullish(),thoughtsTokenCount:d().nullish(),promptTokenCount:d().nullish(),candidatesTokenCount:d().nullish(),totalTokenCount:d().nullish(),trafficType:o().nullish(),serviceTier:o().nullish(),promptTokensDetails:Ge,candidatesTokensDetails:Ge}),qe=()=>s({urlMetadata:i(s({retrievedUrl:o(),urlRetrievalStatus:o()})).nullish()}),Je=p(()=>D(s({candidates:i(s({content:We().nullish().or(s({}).strict()),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(H()).nullish(),groundingMetadata:He().nullish(),urlContextMetadata:qe().nullish()})),usageMetadata:Ke.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(H()).nullish()}).nullish()}))),Ye=p(()=>D(s({candidates:i(s({content:We().nullish(),finishReason:o().nullish(),finishMessage:o().nullish(),safetyRatings:i(H()).nullish(),groundingMetadata:He().nullish(),urlContextMetadata:qe().nullish()})).nullish(),usageMetadata:Ke.nullish(),promptFeedback:s({blockReason:o().nullish(),safetyRatings:i(H()).nullish()}).nullish()}))),Xe=M({id:`google.code_execution`,inputSchema:s({language:o().describe(`The programming language of the code.`),code:o().describe(`The code to be executed.`)}),outputSchema:s({outcome:o().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:o().describe(`The output from the code execution.`)})}),Ze=M({id:`google.enterprise_web_search`,inputSchema:p(()=>D(s({}))),outputSchema:p(()=>D(s({})))});s({fileSearchStoreNames:i(o()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:d().int().positive().describe(`The number of file search retrieval chunks to retrieve.`).optional(),metadataFilter:o().describe(`Metadata filter to apply to the file search retrieval documents. See https://google.aip.dev/160 for the syntax of the filter expression.`).optional()}).passthrough();var Qe=M({id:`google.file_search`,inputSchema:p(()=>D(s({}))),outputSchema:p(()=>D(s({})))}),$e=M({id:`google.google_maps`,inputSchema:p(()=>D(s({}))),outputSchema:p(()=>D(s({})))}),et=s({searchTypes:s({webSearch:s({}).optional(),imageSearch:s({}).optional()}).optional(),timeRangeFilter:s({startTime:o(),endTime:o()}).optional()}).passthrough(),tt={googleSearch:M({id:`google.google_search`,inputSchema:p(()=>D(s({}))),outputSchema:p(()=>D(s({})))}),enterpriseWebSearch:Ze,googleMaps:$e,urlContext:M({id:`google.url_context`,inputSchema:p(()=>D(s({}))),outputSchema:p(()=>D(s({})))}),fileSearch:Qe,codeExecution:Xe,vertexRagStore:M({id:`google.vertex_rag_store`,inputSchema:p(()=>D(s({}))),outputSchema:p(()=>D(s({})))})},nt=p(()=>D(s({personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:f([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish(),googleSearch:et.optional()}))),rt=class e{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v4`}static[w](e){return _({modelId:e.modelId,config:e.config})}static[O](t){return new e(t.modelId,{},t.config)}get maxImagesPerCall(){return this.settings.maxImagesPerCall==null?it(this.modelId)?10:4:this.settings.maxImagesPerCall}get provider(){return this.config.provider}async doGenerate(e){return it(this.modelId)?this.doGenerateGemini(e):this.doGenerateImagen(e)}async doGenerateImagen(e){var t;let{prompt:n,n:r=1,size:i,aspectRatio:a=`1:1`,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(u!=null&&u.length>0)throw Error(`Google Gemini API does not support image editing with Imagen models. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);if(d!=null)throw Error(`Google Gemini API does not support image editing with masks. Use Google Vertex AI (@ai-sdk/google-vertex) for image editing capabilities.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),o!=null&&f.push({type:`unsupported`,feature:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await b({provider:`google`,providerOptions:s,schema:nt}),h=((t=this.config._internal)?.currentDate)?.call(t)??new Date,g={sampleCount:r};if(a!=null&&(g.aspectRatio=a),p){let{googleSearch:e,...t}=p;e!=null&&f.push({type:`unsupported`,feature:`googleSearch`,details:`Google Search grounding is only supported on Gemini image models.`}),Object.assign(g,t)}let _={instances:[{prompt:n}],parameters:g},{responseHeaders:v,value:y}=await R({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:P(this.config.headers?await m(this.config.headers):void 0,c),body:_,failedResponseHandler:z,successfulResponseHandler:j(at),abortSignal:l,fetch:this.config.fetch});return{images:y.predictions.map(e=>e.bytesBase64Encoded),warnings:f,providerMetadata:{google:{images:y.predictions.map(()=>({}))}},response:{timestamp:h,modelId:this.modelId,headers:v}}}async doGenerateGemini(e){var t;let{prompt:n,n:r,size:i,aspectRatio:a,seed:o,providerOptions:s,headers:c,abortSignal:l,files:u,mask:d}=e,f=[];if(d!=null)throw Error(`Gemini image models do not support mask-based image editing.`);if(r!=null&&r>1)throw Error(`Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter.`);i!=null&&f.push({type:`unsupported`,feature:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."});let p=[];if(n!=null&&p.push({type:`text`,text:n}),u!=null&&u.length>0)for(let e of u)e.type===`url`?p.push({type:`file`,data:{type:`url`,url:new URL(e.url)},mediaType:`image/*`}):p.push({type:`file`,data:{type:`data`,data:typeof e.data==`string`?e.data:new Uint8Array(e.data)},mediaType:e.mediaType});let m=[{role:`user`,content:p}],h=await b({provider:`google`,providerOptions:s,schema:nt}),{googleSearch:g,..._}=s?.google??{},v=await new Pe(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??A}).doGenerate({prompt:m,seed:o,providerOptions:{google:{responseModalities:[`IMAGE`],imageConfig:a?{aspectRatio:a}:void 0,..._}},tools:h?.googleSearch==null?void 0:[{type:`provider`,id:`google.google_search`,name:`google_search`,args:h.googleSearch}],headers:c,abortSignal:l}),y=((t=this.config._internal)?.currentDate)?.call(t)??new Date,x=[];for(let e of v.content)e.type===`file`&&e.mediaType.startsWith(`image/`)&&e.data.type===`data`&&x.push(N(e.data.data));return{images:x,warnings:f,providerMetadata:{google:{...v.providerMetadata?.google??{},images:x.map(()=>({}))}},response:{timestamp:y,modelId:this.modelId,headers:v.response?.headers},usage:v.usage?{inputTokens:v.usage.inputTokens.total,outputTokens:v.usage.outputTokens.total,totalTokens:(v.usage.inputTokens.total??0)+(v.usage.outputTokens.total??0)}:void 0}}};function it(e){return e.startsWith(`gemini-`)}var at=p(()=>D(s({predictions:i(s({bytesBase64Encoded:o()})).default([])}))),ot=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile(t){let n=await b({provider:`google`,providerOptions:t.providerOptions,schema:ct}),r=this.config.headers(),i=this.config.fetch??globalThis.fetch,a=[];t.filename!=null&&a.push({type:`unsupported`,feature:`filename`});let o=re(t.data),s=t.mediaType,c=n?.displayName,l=await i(`${this.config.baseURL.replace(/\/v1beta$/,``)}/upload/v1beta/files`,{method:`POST`,headers:{...r,"X-Goog-Upload-Protocol":`resumable`,"X-Goog-Upload-Command":`start`,"X-Goog-Upload-Header-Content-Length":String(o.length),"X-Goog-Upload-Header-Content-Type":s,"Content-Type":`application/json`},body:JSON.stringify({file:{...c==null?{}:{display_name:c}}})});if(!l.ok){let t=await l.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to initiate resumable upload: ${l.status} ${t}`})}let u=l.headers.get(`x-goog-upload-url`);if(!u)throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`No upload URL returned from initiation request`});let d=await i(u,{method:`POST`,headers:{"Content-Length":String(o.length),"X-Goog-Upload-Offset":`0`,"X-Goog-Upload-Command":`upload, finalize`},body:o});if(!d.ok){let t=await d.text();throw new e({name:`GOOGLE_FILES_UPLOAD_ERROR`,message:`Failed to upload file data: ${d.status} ${t}`})}let f=(await d.json()).file,p=n?.pollIntervalMs??2e3,m=n?.pollTimeoutMs??3e5,h=Date.now();for(;f.state===`PROCESSING`;){if(Date.now()-h>m)throw new e({name:`GOOGLE_FILES_UPLOAD_TIMEOUT`,message:`File processing timed out after ${m}ms`});await k(p);let{value:t}=await L({url:`${this.config.baseURL}/${f.name}`,headers:P(r),successfulResponseHandler:j(st),failedResponseHandler:z,fetch:this.config.fetch});f=t}if(f.state===`FAILED`)throw new e({name:`GOOGLE_FILES_UPLOAD_FAILED`,message:`File processing failed for ${f.name}`});return{warnings:a,providerReference:{google:f.uri},mediaType:f.mimeType??t.mediaType,providerMetadata:{google:{name:f.name,displayName:f.displayName,mimeType:f.mimeType,sizeBytes:f.sizeBytes,state:f.state,uri:f.uri,...f.createTime==null?{}:{createTime:f.createTime},...f.updateTime==null?{}:{updateTime:f.updateTime},...f.expirationTime==null?{}:{expirationTime:f.expirationTime},...f.sha256Hash==null?{}:{sha256Hash:f.sha256Hash}}}}}},st=p(()=>D(s({name:o(),displayName:o().nullish(),mimeType:o(),sizeBytes:o().nullish(),createTime:o().nullish(),updateTime:o().nullish(),expirationTime:o().nullish(),sha256Hash:o().nullish(),uri:o(),state:o()}))),ct=p(()=>D(s({displayName:o().nullish(),pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish()}).passthrough())),lt=p(()=>D(s({pollIntervalMs:d().positive().nullish(),pollTimeoutMs:d().positive().nullish(),personGeneration:f([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),negativePrompt:o().nullish(),referenceImages:i(s({bytesBase64Encoded:o().nullish(),gcsUri:o().nullish()})).nullish()}).passthrough())),ut=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}get provider(){return this.config.provider}get maxVideosPerCall(){return 4}async doGenerate(t){var n;let r=((n=this.config._internal)?.currentDate)?.call(n)??new Date,i=[],a=await b({provider:`google`,providerOptions:t.providerOptions,schema:lt}),o=[{}],s=o[0];if(t.prompt!=null&&(s.prompt=t.prompt),t.image!=null)if(t.image.type===`url`)i.push({type:`unsupported`,feature:`URL-based image input`,details:`Google Generative AI video models require base64-encoded images. URL will be ignored.`});else{let e=typeof t.image.data==`string`?t.image.data:ie(t.image.data);s.image={inlineData:{mimeType:t.image.mediaType||`image/png`,data:e}}}a?.referenceImages!=null&&(s.referenceImages=a.referenceImages.map(e=>e.bytesBase64Encoded?{inlineData:{mimeType:`image/png`,data:e.bytesBase64Encoded}}:e.gcsUri?{gcsUri:e.gcsUri}:e));let c={sampleCount:t.n};if(t.aspectRatio&&(c.aspectRatio=t.aspectRatio),t.resolution&&(c.resolution={"1280x720":`720p`,"1920x1080":`1080p`,"3840x2160":`4k`}[t.resolution]||t.resolution),t.duration&&(c.durationSeconds=t.duration),t.seed&&(c.seed=t.seed),a!=null){let e=a;e.personGeneration!==void 0&&e.personGeneration!==null&&(c.personGeneration=e.personGeneration),e.negativePrompt!==void 0&&e.negativePrompt!==null&&(c.negativePrompt=e.negativePrompt);for(let[t,n]of Object.entries(e))[`pollIntervalMs`,`pollTimeoutMs`,`personGeneration`,`negativePrompt`,`referenceImages`].includes(t)||(c[t]=n)}let{value:l}=await R({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:P(await m(this.config.headers),t.headers),body:{instances:o,parameters:c},successfulResponseHandler:j(dt),failedResponseHandler:z,abortSignal:t.abortSignal,fetch:this.config.fetch}),u=l.name;if(!u)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No operation name returned from API`});let d=a?.pollIntervalMs??1e4,f=a?.pollTimeoutMs??6e5,p=Date.now(),h=l,g;for(;!h.done;){if(Date.now()-p>f)throw new e({name:`GOOGLE_VIDEO_GENERATION_TIMEOUT`,message:`Video generation timed out after ${f}ms`});if(await k(d),t.abortSignal?.aborted)throw new e({name:`GOOGLE_VIDEO_GENERATION_ABORTED`,message:`Video generation request was aborted`});let{value:n,responseHeaders:r}=await L({url:`${this.config.baseURL}/${u}`,headers:P(await m(this.config.headers),t.headers),successfulResponseHandler:j(dt),failedResponseHandler:z,abortSignal:t.abortSignal,fetch:this.config.fetch});h=n,g=r}if(h.error)throw new e({name:`GOOGLE_VIDEO_GENERATION_FAILED`,message:`Video generation failed: ${h.error.message}`});let _=h.response;if(!_?.generateVideoResponse?.generatedSamples||_.generateVideoResponse.generatedSamples.length===0)throw new e({name:`GOOGLE_VIDEO_GENERATION_ERROR`,message:`No videos in response. Response: ${JSON.stringify(h)}`});let v=[],y=[],x=(await m(this.config.headers))?.[`x-goog-api-key`];for(let e of _.generateVideoResponse.generatedSamples)if(e.video?.uri){let t=x&&S(e.video.uri,this.config.baseURL)?`${e.video.uri}${e.video.uri.includes(`?`)?`&`:`?`}key=${x}`:e.video.uri;v.push({type:`url`,url:t,mediaType:`video