murmur-rag 2.1.4 → 2.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/{anthropic-dwkw2zf0.js → anthropic-9g8r07a0.js} +2 -2
- package/dist/cdn/chunk-c0ztxsjw.js +1 -0
- package/dist/cdn/{embed-zckjbrcx.js → embed-3x3yz3jw.js} +3 -3
- package/dist/cdn/embed-b072jtkd.js +9 -0
- package/dist/cdn/{embed-5hve1gb4.js → embed-gx1epk52.js} +5 -5
- package/dist/cdn/{embed-wyxkzaf2.js → embed-hm6mmwpk.js} +2 -2
- package/dist/cdn/{embed-3swpcbya.js → embed-pm1dj76g.js} +25 -25
- package/dist/cdn/{embed-7xhp36fz.js → embed-q2zmgyqj.js} +2 -2
- package/dist/cdn/{embed-jq13zkzk.js → embed-strrtkwa.js} +1 -1
- package/dist/cdn/{google-gqhzbbx9.js → google-8ag1bn64.js} +3 -3
- package/dist/cdn/{index-6xnn7k2v.js → index-27ae3wqx.js} +1 -1
- package/dist/cdn/{index-tjxzgn54.js → index-3hkf4rah.js} +1 -1
- package/dist/cdn/{index-qp16wec2.js → index-ec42kn0e.js} +1 -1
- package/dist/cdn/index-em6py5z5.js +1 -0
- package/dist/cdn/{index-rxaj62j2.js → index-xz31ft5m.js} +1 -1
- package/dist/cdn/{mistral-sr36hy2t.js → mistral-x5wz2kx2.js} +1 -1
- package/dist/cdn/murmur-s4gkmy66.js +5 -0
- package/dist/cdn/murmur.js +6 -6
- package/dist/cdn/{openai-ydzb54fp.js → openai-84wvv6cp.js} +5 -5
- package/dist/cdn/{openai-compatible-g3jhmg6n.js → openai-compatible-5qanv34a.js} +2 -2
- package/dist/cdn/retriever-brdwdchq.js +1 -0
- package/dist/cdn/{transformers.web-jpvp33st.js → transformers.web-3m8jygmc.js} +1 -1
- package/dist/lib/chunks/index-7xc57jeh.js +86 -0
- package/dist/lib/chunks/{index-q0vxh483.js → index-9ybqwzx2.js} +43 -23
- package/dist/lib/chunks/{index-35jjv3kg.js → index-ahy8h3ks.js} +9 -4
- package/dist/lib/chunks/{index-qzy7ezw0.js → index-pjwdwban.js} +1 -1
- package/dist/lib/chunks/{murmur-z8e9regf.js → murmur-5e79jear.js} +2 -2
- package/dist/lib/chunks/{retriever-v2py7tyc.js → retriever-62r4an0v.js} +1 -1
- package/dist/lib/embed.js +2 -2
- package/dist/lib/index.js +8 -4
- package/dist/lib/rag/index.js +7 -3
- package/dist/lib/widget/index.js +2 -2
- package/dist/types/rag/ground.d.ts +14 -3
- package/dist/types/rag/index.d.ts +1 -1
- package/package.json +1 -1
- package/dist/cdn/chunk-nhd6pd73.js +0 -1
- package/dist/cdn/embed-ecgnvx0r.js +0 -9
- package/dist/cdn/index-m7fjbsrx.js +0 -1
- package/dist/cdn/murmur-4h6m9e42.js +0 -5
- package/dist/cdn/retriever-xmnq9gye.js +0 -1
- package/dist/lib/chunks/index-kcw6fd5n.js +0 -58
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{oe,Ie}from"./embed-
|
|
2
|
-
`):"Tool executed successfully."},...re.length>0?{parts:re}:{}}})}function lo(f,w,x,A,N=!0){for(let B of x)switch(B.type){case"text":f.push({functionResponse:{...N&&A!=null?{id:A}:{},name:w,response:{name:w,content:B.text}}});break;case"file":if(B.data.type==="data"){let re=z(B.mediaType);f.push({inlineData:{mimeType:O({part:B}),data:M(B.data.data)}},{text:`Tool executed successfully and returned this ${re==="image"?"image":"file"} as a response`})}else f.push({text:JSON.stringify(B)});break;default:f.push({text:JSON.stringify(B)})}}function uo(f,w){let x=[],A=[],N=!0,B=w?.isGemmaModel??!1,re=w?.isGemini3Model??!1,ee=w?.onWarning,V=w?.providerOptionsNames??["google"],pe=!V.includes("google"),ce=w?.supportsFunctionResponseParts??!0,Re=w?.includeFunctionCallIds??!0,Le=w?.supportedFunctionResponseUrls??{},Ce=!1,Ee=[],je=(ye)=>(Ee.push(ye),Ce=!0,oo),Ne=(ye)=>{for(let ie of V){let be=ye.providerOptions?.[ie];if(be!=null)return be}if(pe)return ye.providerOptions?.google;return ye.providerOptions?.googleVertex??ye.providerOptions?.vertex};for(let{role:ye,content:ie}of f)switch(ye){case"system":if(!N)throw new u({functionality:"system messages are only supported at the beginning of the conversation"});x.push({text:ie});break;case"user":{N=!1;let be=[];for(let ne of ie)switch(ne.type){case"text":be.push({text:ne.text});break;case"file":switch(ne.data.type){case"url":be.push({fileData:{mimeType:O({part:ne}),fileUri:ne.data.url.protocol==="gs:"&&ne.data.originalUrl!=null?ne.data.originalUrl:ne.data.url.toString()}});break;case"reference":if(pe)throw new u({functionality:"file parts with provider references"});be.push({fileData:{mimeType:O({part:ne}),fileUri:H({reference:ne.data.reference,provider:"google"})}});break;case"text":be.push({inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))}});break;case"data":be.push({inlineData:{mimeType:O({part:ne}),data:M(ne.data.data)}})}}A.push({role:"user",parts:be});break}case"assistant":{N=!1;let be=!1;A.push({role:"model",parts:ie.map((ne)=>{let se=Ne(ne),Ue=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;switch(ne.type){case"text":return ne.text.length===0?void 0:{text:ne.text,thoughtSignature:Ue};case"reasoning":return ne.text.length===0?void 0:{text:ne.text,thought:!0,thoughtSignature:Ue};case"reasoning-file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},thought:!0,thoughtSignature:Ue}}break;case"file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(pe)throw new u({functionality:"file parts with provider references"});return{fileData:{mimeType:ne.mediaType,fileUri:H({reference:ne.data.reference,provider:"google"})},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"text":return{inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue}}break;case"tool-call":{if(ne.providerExecuted===!0&&ne.toolName==="code_execution")return{executableCode:yn.parse(typeof ne.input==="string"?Q(ne.input):ne.input)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0,We=De!=null&&qe!=null,nt=Ue??(re&&!(!We&&Ue==null&&be)?je(ne.toolName):void 0);if(!We&&Ue!=null)be=!0;if(We)return{toolCall:{toolType:qe,args:typeof ne.input==="string"?Q(ne.input):ne.input,id:De},thoughtSignature:nt};return{functionCall:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,args:ne.input},thoughtSignature:nt}}case"tool-result":{if(ne.toolName==="code_execution"&&ne.output.type==="json")return{codeExecutionResult:vn.parse(ne.output.value)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0;if(De&&qe)return{toolResponse:{toolType:qe,response:ne.output.type==="json"?ne.output.value:{},id:De},thoughtSignature:Ue};return}}}).filter((ne)=>ne!==void 0)});break}case"tool":{N=!1;let be=[];for(let ne of ie){if(ne.type==="tool-approval-response")continue;let se=Ne(ne),Ue=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,De=se?.serverToolType!=null?String(se.serverToolType):void 0;if(Ue&&De){let We=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;if(A.length>0){let nt=A[A.length-1];if(nt.role==="model"){nt.parts.push({toolResponse:{toolType:De,response:ne.output.type==="json"?ne.output.value:{},id:Ue},thoughtSignature:We});continue}}}let qe=ne.output;if(qe.type==="content")if(ce)ro(be,ne.toolName,qe.value,ne.toolCallId,Re,Le);else lo(be,ne.toolName,qe.value,ne.toolCallId,Re);else{let We=qe.type==="error-text"||qe.type==="error-json"||qe.type==="execution-denied";be.push({functionResponse:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,response:{name:ne.toolName,...We?{error:qe.type==="execution-denied"?qe.reason??"Tool call execution denied.":
|
|
1
|
+
import{oe,Ie}from"./embed-hm6mmwpk.js";import{tt}from"./embed-q2zmgyqj.js";import{m,b,P,me,u,e,r,c,v,Ae,o,t,U,l,y,i,n,G,k,T,d,Oe,ue,fe,ae,j,X,M,we,en,te,le,xe,ke,Z,F,Te,z,K,He,Me,rn,de,C,R,L,Ze,he,W,Se,lt,ge,Q,a,s,q,J,h,g,ve,S,_,O,H,I,D,p,_e,E,Y}from"./embed-pm1dj76g.js";var zn="4.0.107",fn=()=>t({code:r().nullable(),message:e(),status:e(),details:o(v()).nullish()}),Jn=a(()=>s(t({error:fn()}))),Xe=I({errorSchema:Jn,errorToMessage:(f)=>f.error.message}),Yn=()=>l([t({text:e()}),t({inlineData:t({mimeType:e(),data:e()})}),t({fileData:t({fileUri:e(),mimeType:e()})})]),Xn=a(()=>s(t({outputDimensionality:r().optional(),taskType:i(["SEMANTIC_SIMILARITY","CLASSIFICATION","CLUSTERING","RETRIEVAL_DOCUMENT","RETRIEVAL_QUERY","QUESTION_ANSWERING","FACT_VERIFICATION","CODE_RETRIEVAL_QUERY"]).optional(),content:o(o(Yn()).min(1).nullable()).optional()}))),Qn=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.specificationVersion="v4",this.maxEmbeddingsPerCall=100,this.supportsParallelCalls=!0,this[rn]=({providerOptions:A,values:N,startIndex:B,endIndex:re})=>{let ee=A?.google?.content;if(!Array.isArray(ee))return A;return zt({multimodalContent:ee,values:N}),{...A,google:{...A?.google,content:ee.slice(B,re)}}},this.modelId=w,this.config=x}async doEmbed({values:w,dimensions:x,headers:A,abortSignal:N,providerOptions:B}){let re=await h({provider:"google",providerOptions:B,schema:Xn});if(w.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:w});let ee=d(this.config.headers?await _(this.config.headers):void 0,A),V=re?.content;if(zt({multimodalContent:V,values:w}),w.length===1){let Le=V?.[0],Ce=w[0]?[{text:w[0]}]:[],Ee=Le!=null?[...Ce,...Le]:[{text:w[0]}],{responseHeaders:je,value:Ne,rawValue:ye}=await g({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:ee,body:{model:`models/${this.modelId}`,content:{parts:Ee},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType},failedResponseHandler:Xe,successfulResponseHandler:p(eo),abortSignal:N,fetch:this.config.fetch});return{warnings:[],embeddings:[Ne.embedding.values],usage:void 0,response:{headers:je,body:ye}}}let{responseHeaders:pe,value:ce,rawValue:Re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:ee,body:{requests:w.map((Le,Ce)=>{let Ee=V?.[Ce],je=Le?[{text:Le}]:[];return{model:`models/${this.modelId}`,content:{role:"user",parts:Ee!=null?[...je,...Ee]:[{text:Le}]},outputDimensionality:re?.outputDimensionality??x,taskType:re?.taskType}})},failedResponseHandler:Xe,successfulResponseHandler:p(Zn),abortSignal:N,fetch:this.config.fetch});return{warnings:[],embeddings:ce.embeddings.map((Le)=>Le.values),usage:void 0,response:{headers:pe,body:Re}}}},Zn=a(()=>s(t({embeddings:o(t({values:o(r())}))}))),eo=a(()=>s(t({embedding:t({values:o(r())})})));function zt({multimodalContent:f,values:w}){if(f!=null&&f.length!==w.length)throw Error(`The number of multimodal content entries (${f.length}) must match the number of values (${w.length}).`)}function Tt(f){return f.includes("/")?f:`models/${f}`}function to({stream:f,getContinuationToken:w,continueStream:x}){let A=f.getReader(),N;return new ReadableStream({async pull(B){while(!0){let{done:re,value:ee}=await A.read();if(!re){if(ee.success){let pe=w(ee.value);if(pe!=null)N=pe}B.enqueue(ee);return}if(N==null){B.close();return}let V=N;N=void 0;try{A=(await x(V)).getReader(),B.enqueue({type:"continuation-start"});return}catch(pe){B.enqueue({success:!1,error:pe,rawValue:void 0}),B.close();return}}},async cancel(B){await A.cancel(B)}})}function Jt(f){if(f==null)return te();let w=f.promptTokenCount??0,x=f.candidatesTokenCount??0,A=f.toolUsePromptTokenCount??0,N=f.cachedContentTokenCount??0,B=f.thoughtsTokenCount??0,re=w+A;return{inputTokens:{total:re,noCache:re-N,cacheRead:N,cacheWrite:void 0},outputTokens:{total:x+B,text:x,reasoning:B},raw:f}}function jt(f,w){if(f==null||w==null)return w??f;return{...f,...w,promptTokenCount:vt(f.promptTokenCount,w.promptTokenCount),candidatesTokenCount:vt(f.candidatesTokenCount,w.candidatesTokenCount),toolUsePromptTokenCount:vt(f.toolUsePromptTokenCount,w.toolUsePromptTokenCount),totalTokenCount:vt(f.totalTokenCount,w.totalTokenCount),cachedContentTokenCount:vt(f.cachedContentTokenCount,w.cachedContentTokenCount),thoughtsTokenCount:vt(f.thoughtsTokenCount,w.thoughtsTokenCount),promptTokensDetails:kt(f.promptTokensDetails,w.promptTokensDetails),cacheTokensDetails:kt(f.cacheTokensDetails,w.cacheTokensDetails),candidatesTokensDetails:kt(f.candidatesTokensDetails,w.candidatesTokensDetails),toolUsePromptTokensDetails:kt(f.toolUsePromptTokensDetails,w.toolUsePromptTokensDetails)}}function vt(f,w){return f==null&&w==null?w??f:(f??0)+(w??0)}function kt(f,w){if(f==null||w==null)return w??f;let x=new Map;for(let{modality:A,tokenCount:N}of[...f,...w])x.set(A,(x.get(A)??0)+N);return Array.from(x,([A,N])=>({modality:A,tokenCount:N}))}var yn=t({language:e().describe("The programming language of the code."),code:e().describe("The code to be executed.")}),vn=t({outcome:e().describe('The outcome of the execution (e.g., "OUTCOME_OK").'),output:e().describe("The output from the code execution.")}),no=S({id:"google.code_execution",inputSchema:yn,outputSchema:vn}),oo="skip_thought_signature_validator",io=/^data:([^;,]+);base64,(.+)$/s;function so(f){let w=io.exec(f);if(w==null)return;return{mediaType:w[1],data:w[2]}}function ao(f){let w=so(f);if(w==null)return;return{inlineData:{mimeType:w.mediaType,data:w.data}}}function Gt(f){if(Array.isArray(f))return f.some(Gt);if(typeof f!=="object"||f===null)return!1;return Object.entries(f).some(([w,x])=>w==="$ref"||Gt(x))}function Yt(f){return Gt(f)?JSON.stringify(f):f}function ro(f,w,x,A,N=!0,B={}){let re=[],ee=[];for(let V of x)switch(V.type){case"text":ee.push(V.text);break;case"file":if(V.data.type==="data")re.push({inlineData:{mimeType:O({part:V}),data:M(V.data.data)}});else if(V.data.type==="url"){let pe=V.data.url.toString(),ce=ao(pe),Re=V.data.url.protocol==="gs:"&&V.data.originalUrl!=null?V.data.originalUrl:pe;if(ce!=null)re.push(ce);else if(K(V.mediaType)&&Ze({url:Re,mediaType:V.mediaType,supportedUrls:B}))re.push({fileData:{mimeType:V.mediaType,fileUri:Re}});else ee.push(JSON.stringify(V))}else ee.push(JSON.stringify(V));break;default:ee.push(JSON.stringify(V))}f.push({functionResponse:{...N&&A!=null?{id:A}:{},name:w,response:{name:w,content:ee.length>0?ee.join(`
|
|
2
|
+
`):"Tool executed successfully."},...re.length>0?{parts:re}:{}}})}function lo(f,w,x,A,N=!0){for(let B of x)switch(B.type){case"text":f.push({functionResponse:{...N&&A!=null?{id:A}:{},name:w,response:{name:w,content:B.text}}});break;case"file":if(B.data.type==="data"){let re=z(B.mediaType);f.push({inlineData:{mimeType:O({part:B}),data:M(B.data.data)}},{text:`Tool executed successfully and returned this ${re==="image"?"image":"file"} as a response`})}else f.push({text:JSON.stringify(B)});break;default:f.push({text:JSON.stringify(B)})}}function uo(f,w){let x=[],A=[],N=!0,B=w?.isGemmaModel??!1,re=w?.isGemini3Model??!1,ee=w?.onWarning,V=w?.providerOptionsNames??["google"],pe=!V.includes("google"),ce=w?.supportsFunctionResponseParts??!0,Re=w?.includeFunctionCallIds??!0,Le=w?.supportedFunctionResponseUrls??{},Ce=!1,Ee=[],je=(ye)=>(Ee.push(ye),Ce=!0,oo),Ne=(ye)=>{for(let ie of V){let be=ye.providerOptions?.[ie];if(be!=null)return be}if(pe)return ye.providerOptions?.google;return ye.providerOptions?.googleVertex??ye.providerOptions?.vertex};for(let{role:ye,content:ie}of f)switch(ye){case"system":if(!N)throw new u({functionality:"system messages are only supported at the beginning of the conversation"});x.push({text:ie});break;case"user":{N=!1;let be=[];for(let ne of ie)switch(ne.type){case"text":be.push({text:ne.text});break;case"file":switch(ne.data.type){case"url":be.push({fileData:{mimeType:O({part:ne}),fileUri:ne.data.url.protocol==="gs:"&&ne.data.originalUrl!=null?ne.data.originalUrl:ne.data.url.toString()}});break;case"reference":if(pe)throw new u({functionality:"file parts with provider references"});be.push({fileData:{mimeType:O({part:ne}),fileUri:H({reference:ne.data.reference,provider:"google"})}});break;case"text":be.push({inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))}});break;case"data":be.push({inlineData:{mimeType:O({part:ne}),data:M(ne.data.data)}})}}A.push({role:"user",parts:be});break}case"assistant":{N=!1;let be=!1;A.push({role:"model",parts:ie.map((ne)=>{let se=Ne(ne),Ue=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;switch(ne.type){case"text":return ne.text.length===0?void 0:{text:ne.text,thoughtSignature:Ue};case"reasoning":return ne.text.length===0?void 0:{text:ne.text,thought:!0,thoughtSignature:Ue};case"reasoning-file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},thought:!0,thoughtSignature:Ue}}break;case"file":switch(ne.data.type){case"url":throw new u({functionality:"File data URLs in assistant messages are not supported"});case"reference":if(pe)throw new u({functionality:"file parts with provider references"});return{fileData:{mimeType:ne.mediaType,fileUri:H({reference:ne.data.reference,provider:"google"})},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"text":return{inlineData:{mimeType:K(ne.mediaType)?ne.mediaType:"text/plain",data:M(new TextEncoder().encode(ne.data.text))},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue};case"data":return{inlineData:{mimeType:ne.mediaType,data:M(ne.data.data)},...se?.thought===!0?{thought:!0}:{},thoughtSignature:Ue}}break;case"tool-call":{if(ne.providerExecuted===!0&&ne.toolName==="code_execution")return{executableCode:yn.parse(typeof ne.input==="string"?Q(ne.input):ne.input)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0,We=De!=null&&qe!=null,nt=Ue??(re&&!(!We&&Ue==null&&be)?je(ne.toolName):void 0);if(!We&&Ue!=null)be=!0;if(We)return{toolCall:{toolType:qe,args:typeof ne.input==="string"?Q(ne.input):ne.input,id:De},thoughtSignature:nt};return{functionCall:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,args:ne.input},thoughtSignature:nt}}case"tool-result":{if(ne.toolName==="code_execution"&&ne.output.type==="json")return{codeExecutionResult:vn.parse(ne.output.value)};let De=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,qe=se?.serverToolType!=null?String(se.serverToolType):void 0;if(De&&qe)return{toolResponse:{toolType:qe,response:ne.output.type==="json"?ne.output.value:{},id:De},thoughtSignature:Ue};return}}}).filter((ne)=>ne!==void 0)});break}case"tool":{N=!1;let be=[];for(let ne of ie){if(ne.type==="tool-approval-response")continue;let se=Ne(ne),Ue=se?.serverToolCallId!=null?String(se.serverToolCallId):void 0,De=se?.serverToolType!=null?String(se.serverToolType):void 0;if(Ue&&De){let We=se?.thoughtSignature!=null?String(se.thoughtSignature):void 0;if(A.length>0){let nt=A[A.length-1];if(nt.role==="model"){nt.parts.push({toolResponse:{toolType:De,response:ne.output.type==="json"?ne.output.value:{},id:Ue},thoughtSignature:We});continue}}}let qe=ne.output;if(qe.type==="content")if(ce)ro(be,ne.toolName,qe.value,ne.toolCallId,Re,Le);else lo(be,ne.toolName,qe.value,ne.toolCallId,Re);else{let We=qe.type==="error-text"||qe.type==="error-json"||qe.type==="execution-denied";be.push({functionResponse:{...Re&&ne.toolCallId!=null?{id:ne.toolCallId}:{},name:ne.toolName,response:{name:ne.toolName,...We?{error:qe.type==="execution-denied"?qe.reason??"Tool call execution denied.":Yt(qe.value)}:{content:Yt(qe.value)}}}})}}A.push({role:"user",parts:be});break}}if(B&&x.length>0&&A.length>0&&A[0].role==="user"){let ye=x.map((ie)=>ie.text).join(`
|
|
3
3
|
|
|
4
4
|
`);A[0].parts.unshift({text:ye+`
|
|
5
5
|
|
|
6
|
-
`})}if(Ce&&ee!=null){let ye=Array.from(new Set(Ee));ee({type:"other",message:`Replayed ${Ee.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${ye.map((ie)=>`\`${ie}\``).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:x.length>0&&!B?{parts:x}:void 0,contents:A}}async function co(f,{abortSignal:w,maxBytes:x,supportedUrls:A={}}){let N=[];for(let B of f){if(B.role==="assistant"){let re=[];for(let ee of B.content)re.push(ee.type==="tool-result"?{...ee,output:await Qt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})}:ee);N.push({...B,content:re});continue}if(B.role==="tool"){let re=[];for(let ee of B.content){if(ee.type!=="tool-result"){re.push(ee);continue}re.push({...ee,output:await Qt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})})}N.push({...B,content:re});continue}N.push(B)}return N}async function Qt(f,{abortSignal:w,maxBytes:x,supportedUrls:A}){if(f.type!=="content")return f;let N=[];for(let B of f.value){if(B.type!=="file"||B.data.type!=="url"){N.push(B);continue}if(Ze({url:B.data.url.toString(),mediaType:B.mediaType,supportedUrls:A})){N.push(B);continue}let re=await Me(B.data.url.toString(),{abortSignal:w,maxBytes:x}),ee=new Uint8Array(await re.arrayBuffer()),V=Te({data:ee,topLevelType:"image"});N.push({...B,data:{type:"data",data:ee},mediaType:V??(re.type&&!K(B.mediaType)?re.type:B.mediaType)})}return{...f,value:N}}function bn(f){let{const:w,properties:x,items:A,additionalProperties:N,anyOf:B,oneOf:re,...ee}=f;return{...ee,...w!==void 0?{enum:[w]}:{},...x!=null?{properties:Zt(x)}:{},...A!=null?{items:Array.isArray(A)?A.map(bt):bt(A)}:{},...N!=null?{additionalProperties:typeof N==="boolean"?N:bt(N)}:{},...B!=null?{anyOf:B.map(bt)}:{},...re!=null?{oneOf:re.map(bt)}:{},...ee.$defs!=null?{$defs:Zt(ee.$defs)}:{}}}function Zt(f){return Object.fromEntries(Object.entries(f).map(([w,x])=>[w,bt(x)]))}function bt(f){return typeof f==="boolean"?f:bn(f)}var Et=a(()=>s(t({responseModalities:o(i(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:r().optional(),includeThoughts:c().optional(),thinkingLevel:i(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:c().optional(),safetySettings:o(t({category:i(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:c().optional(),labels:y(e(),e()).optional(),mediaResolution:i(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:i(["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:i(["1K","2K","4K","512"]).optional(),personGeneration:i(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:i(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:i(["image/jpeg","image/png"]).optional(),compressionQuality:r().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:r(),longitude:r()}).optional()}).optional(),streamFunctionCallArguments:c().optional(),serviceTier:i(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:i(["priority","flex","standard"]).optional(),requestType:i(["shared"]).optional()}))),po=/(^|[/.])gemini-1(?:[.-]|$)/i,go=/(^|[/.])gemini-2(?:[.-]|$)/i,ho=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,mo=/(^|[/.])gemini-/i;function fo(f){return po.test(f)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(f)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(f)}function At(f){let w=mo.test(f),x=go.test(f),A=fo(f),N=w&&!(A||x);return{supportsGemini2Tools:w&&!A||f.toLowerCase().includes("nano-banana"),supportsFileSearch:ho.test(f)||N,usesGemini3Features:N}}function yo({tools:f,toolChoice:w,modelId:x,isVertexProvider:A=!1}){f=f?.length?f:void 0;let N=[],{supportsGemini2Tools:B,supportsFileSearch:re,usesGemini3Features:ee}=At(x);if(f==null)return{tools:void 0,toolConfig:void 0,toolWarnings:N};let V=f.some((Ce)=>Ce.type==="function"),pe=f.some((Ce)=>Ce.type==="provider");if(V&&pe&&!ee)N.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(pe){let Ce=[];if(f.filter((Ee)=>Ee.type==="provider").forEach((Ee)=>{switch(Ee.id){case"google.google_search":if(B)Ce.push({googleSearch:{...Ee.args}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(B)Ce.push({enterpriseWebSearch:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(B)Ce.push({urlContext:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(B)Ce.push({codeExecution:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(re)Ce.push({fileSearch:{...Ee.args}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(B)Ce.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:Ee.args.ragCorpus},similarity_top_k:Ee.args.topK}}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(B)Ce.push({googleMaps:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`})}}),V&&ee&&Ce.length>0){let Ee=[];for(let Ne of f)if(Ne.type==="function")Ee.push(en(Ne));let je={functionCallingConfig:{mode:"VALIDATED"},...!A&&{includeServerSideToolInvocations:!0}};if(w!=null)switch(w.type){case"auto":break;case"none":je.functionCallingConfig={mode:"NONE"};break;case"required":je.functionCallingConfig={mode:"ANY"};break;case"tool":je.functionCallingConfig={mode:"ANY",allowedFunctionNames:[w.toolName]}}return{tools:[...Ce,{functionDeclarations:Ee}],toolConfig:je,toolWarnings:N}}return{tools:Ce.length>0?Ce:void 0,toolConfig:void 0,toolWarnings:N}}let ce=[],Re=!1;for(let Ce of f)switch(Ce.type){case"function":if(ce.push(en(Ce)),Ce.strict===!0)Re=!0;break;default:N.push({type:"unsupported",feature:`function tool ${Ce.name}`})}if(w==null)return{tools:[{functionDeclarations:ce}],toolConfig:Re?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:N};let Le=w.type;switch(Le){case"auto":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:Re?"VALIDATED":"AUTO"}},toolWarnings:N};case"none":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:N};case"required":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:N};case"tool":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[w.toolName]}},toolWarnings:N};default:throw new u({functionality:`tool choice type: ${Le}`})}}function en(f){return{name:f.name,description:f.description??"",parametersJsonSchema:f.inputSchema}}var vo=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(f){let w="";for(let x of f){let A=x.jsonPath.endsWith("[]"),N=(A?x.jsonPath.slice(0,-2):x.jsonPath).replace(/^\$\./,"");if(!N||N==="$")continue;let B=bo(N),re=_o(this.accumulatedArgs,B);if(x.stringValue!=null&&re!==void 0){let V=JSON.stringify(x.stringValue).slice(1,-1);Ut(this.accumulatedArgs,B,re+x.stringValue),w+=V;continue}let ee=Co(x);if(ee==null){if(re!==void 0||x.willContinue===!0)continue;Ut(this.accumulatedArgs,B,A?[]:{}),w+=this.emitContainer(B,A);continue}Ut(this.accumulatedArgs,B,ee.value),w+=this.emitNavigationTo(B,x,ee.json)}return this.jsonText+=w,{currentJSON:this.accumulatedArgs,textDelta:w}}finalize(){let f=JSON.stringify(this.accumulatedArgs);return{finalJSON:f,closingDelta:f.slice(this.jsonText.length)}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(f,w,x){let A="";if(this.stringOpen)A+='"',this.stringOpen=!1;A+=this.ensureRoot();let N=f.slice(0,-1),B=f[f.length-1],re=this.findCommonStackDepth(N);return A+=this.closeDownTo(re),A+=this.openDownTo(N,B),A+=this.emitLeaf(B,w,x),A}emitContainer(f,w){let x="";if(this.stringOpen)x+='"',this.stringOpen=!1;x+=this.ensureRoot();let A=this.findCommonStackDepth(f);return x+=this.closeDownTo(A),x+=this.openDownTo(f,w?0:""),x}findCommonStackDepth(f){let w=Math.min(this.pathStack.length-1,f.length),x=0;for(let A=0;A<w;A++)if(this.pathStack[A+1].segment===f[A])x++;else break;return x+1}closeDownTo(f){let w="";while(this.pathStack.length>f){let x=this.pathStack.pop();w+=x.isArray?"]":"}"}return w}openDownTo(f,w){let x="",A=this.pathStack.length-1;for(let N=A;N<f.length;N++){let B=f[N],re=this.pathStack[this.pathStack.length-1];if(re.childCount>0)x+=",";if(re.childCount++,typeof B==="string")x+=`${JSON.stringify(B)}:`;let ee=typeof(N+1<f.length?f[N+1]:w)==="number";x+=ee?"[":"{",this.pathStack.push({segment:B,isArray:ee,childCount:0})}return x}emitLeaf(f,w,x){let A="",N=this.pathStack[this.pathStack.length-1];if(N.childCount>0)A+=",";if(N.childCount++,typeof f==="string")A+=`${JSON.stringify(f)}:`;if(w.stringValue!=null&&w.willContinue)A+=x.slice(0,-1),this.stringOpen=!0;else A+=x;return A}};function bo(f){let w=[];for(let x of f.split(".")){let A=x.indexOf("[");if(A===-1)w.push(x);else{if(A>0)w.push(x.slice(0,A));for(let N of x.matchAll(/\[(\d+)\]/g))w.push(parseInt(N[1],10))}}return w}var To=Object.prototype.hasOwnProperty;function Tn(f,w){return To.call(f,w)}function nn(f,w,x){Object.defineProperty(f,w,{value:x,enumerable:!0,configurable:!0,writable:!0})}function _o(f,w){let x=f;for(let A of w){if(x==null||typeof x!=="object")return;let N=x;if(!Tn(N,A))return;x=N[A]}return x}function Ut(f,w,x){let A=f;for(let N=0;N<w.length-1;N++){let B=w[N],re=w[N+1];if(!Tn(A,B)||A[B]==null)nn(A,B,typeof re==="number"?[]:{});A=A[B]}nn(A,w[w.length-1],x)}function Co(f){let w=f.stringValue??f.numberValue??f.boolValue;if(w!=null)return{value:w,json:JSON.stringify(w)};if("nullValue"in f)return{value:null,json:"null"}}function on({finishReason:f,hasToolCalls:w}){switch(f){case"STOP":return w?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":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 wo=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],So=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,Io={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},Ct=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x,this.generateId=x.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:w,config:x,options:{prompt:A,maxOutputTokens:N,temperature:B,topP:re,topK:ee,frequencyPenalty:V,presencePenalty:pe,stopSequences:ce,responseFormat:Re,seed:Le,tools:Ce,toolChoice:Ee,reasoning:je,providerOptions:Ne,abortSignal:ye},isStreaming:ie=!1}){let be=[],ne=x.provider.includes("vertex")?["googleVertex","vertex"]:["google"],se;for(let st of ne)if(se=await h({provider:st,providerOptions:Ne,schema:Et}),se!=null)break;if(se==null&&!ne.includes("google"))se=await h({provider:"google",providerOptions:Ne,schema:Et});let Ue=x.provider.startsWith("google.vertex.");if(Ce?.some((st)=>st.type==="provider"&&st.id==="google.vertex_rag_store")&&!Ue)be.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 (${x.provider}).`});if(se?.streamFunctionCallArguments&&!Ue)be.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${x.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(se?.serviceTier&&Ue)be.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"});if((se?.sharedRequestType||se?.requestType)&&!Ue)be.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${x.provider}).`});let De=Ue&&(se?.sharedRequestType||se?.requestType)?{...se.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":se.sharedRequestType},...se.requestType&&{"X-Vertex-AI-LLM-Request-Type":se.requestType}}:void 0,qe=Ue?void 0:se?.serviceTier,We=se?.imageConfig;if(We!=null&&!Ue){let{personGeneration:st,prominentPeople:it,imageOutputOptions:wt,...St}=We,Ye=Object.entries({personGeneration:st,prominentPeople:it,imageOutputOptions:wt}).filter(([,Ge])=>Ge!=null).map(([Ge])=>`'imageConfig.${Ge}'`);if(Ye.length>0)be.push({type:"other",message:`${Ye.join(", ")} ${Ye.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${x.provider}).`}),We=St}let nt=w.toLowerCase().startsWith("gemma-"),Ke=!Ue&&So.test(w);if(Ke&&V!=null)be.push({type:"unsupported",feature:"frequencyPenalty"});if(Ke&&pe!=null)be.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Qe}=At(w),pt=Qe&&x.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?Io:void 0,{contents:ze,systemInstruction:ot}=uo(x.downloadToolResultFiles?await co(A,{abortSignal:ye,maxBytes:x.downloadToolResultFiles.maxBytes,supportedUrls:pt}):A,{isGemmaModel:nt,isGemini3Model:Qe,onWarning:(st)=>be.push(st),providerOptionsNames:ne,supportsFunctionResponseParts:Qe,includeFunctionCallIds:!Ue,supportedFunctionResponseUrls:pt}),{tools:Ve,toolConfig:at,toolWarnings:rt}=yo({tools:Ce,toolChoice:Ee,modelId:w,isVertexProvider:Ue}),dt=le({tools:Ce,providerToolNames:{"google.code_execution":"code_execution"}}),Fe=se?.thinkingConfig?.thinkingBudget!=null||se?.thinkingConfig?.thinkingLevel!=null?void 0:Ro({reasoning:je,modelId:w,warnings:be}),et=se?.thinkingConfig||Fe?{...Fe,...se?.thinkingConfig}:void 0,Je=ie&&Ue?se?.streamFunctionCallArguments??!1:void 0,Be=se?.threshold,Pe=se?.safetySettings??(Be!=null?wo.map((st)=>({category:st,threshold:Be})):void 0),ut=at||Je||se?.retrievalConfig?{...at,...Je&&{functionCallingConfig:{...at?.functionCallingConfig,streamFunctionCallArguments:!0}},...se?.retrievalConfig&&{retrievalConfig:se.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:N,temperature:B,topK:ee,topP:re,frequencyPenalty:Ke?void 0:V,presencePenalty:Ke?void 0:pe,stopSequences:ce,seed:Le,responseMimeType:Re?.type==="json"?"application/json":void 0,responseJsonSchema:Re?.type==="json"&&Re.schema!=null&&(se?.structuredOutputs??!0)?bn(Re.schema):void 0,...se?.audioTimestamp&&{audioTimestamp:se.audioTimestamp},responseModalities:se?.responseModalities,thinkingConfig:et,...se?.mediaResolution&&{mediaResolution:se.mediaResolution},...We&&{imageConfig:We}},contents:ze,systemInstruction:nt?void 0:ot,safetySettings:Pe,tools:Ve,toolConfig:ut,cachedContent:se?.cachedContent,labels:se?.labels,serviceTier:qe,...se?.continuationToken!=null&&{continuationToken:se.continuationToken}},warnings:[...be,...rt],providerOptionsNames:ne,extraHeaders:De,toolNameMapping:dt}}async getArgs(w,{isStreaming:x=!1}={}){let{responseFormat:A,tools:N,toolChoice:B}=w,re;if(A?.type==="json"&&A.schema!=null&&N?.some((ee)=>ee.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!At(this.modelId).usesGemini3Features||B?.type==="required"||B?.type==="tool")){let ee="json";for(let V=1;N.some((pe)=>pe.name===ee);V++)ee=`json_${V}`;re={type:"function",name:ee,description:A.description??"Respond with a JSON object.",inputSchema:A.schema}}return{...await f.prepareRequest({modelId:this.modelId,config:this.config,options:re==null?w:{...w,responseFormat:void 0,tools:[...N??[],re],toolChoice:B?.type==="tool"?B:B?.type==="none"?{type:"tool",toolName:re.name}:{type:"required"}},isStreaming:x}),jsonResponseToolName:re?.name}}static convertGenerateContentResponse({config:w,response:x,warnings:A,providerOptionsNames:N,toolNameMapping:B,jsonResponseToolName:re,initialPromptTokenCount:ee,groundingMetadataPerRequest:V}){let pe=(se)=>Object.fromEntries(N.map((Ue)=>[Ue,se])),ce=x.candidates?.[0],Re=x.promptFeedback?.blockReason,Le=an(Re)?Re:void 0,Ce=ce?.finishReason==null&&Le!=null,Ee=ce?.finishReason??Le,je=[],Ne=ce?.content?.parts??[],ye=x.usageMetadata,ie,be;for(let se of Ne)if("executableCode"in se&&se.executableCode?.code){let Ue=w.generateId();ie=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:B?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(se.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in se&&se.codeExecutionResult)je.push({type:"tool-result",toolCallId:ie,toolName:B?.toCustomToolName("code_execution")??"code_execution",result:{outcome:se.codeExecutionResult.outcome,output:se.codeExecutionResult.output??""}});else if("text"in se&&se.text!=null){if(re!=null&&se.thought!==!0)continue;let Ue=se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0;if(se.text.length===0){if(Ue!=null&&je.length>0){let De=je[je.length-1];De.providerMetadata=Ue}}else je.push({type:se.thought===!0?"reasoning":"text",text:se.text,providerMetadata:Ue})}else if("functionCall"in se&&se.functionCall.name!=null){if(se.functionCall.name===re){je.push({type:"text",text:typeof se.functionCall.args==="string"?se.functionCall.args:JSON.stringify(se.functionCall.args??{}),...se.thoughtSignature?{providerMetadata:pe({thoughtSignature:se.thoughtSignature})}:{}});continue}je.push({type:"tool-call",toolCallId:se.functionCall.id||w.generateId(),toolName:se.functionCall.name,input:JSON.stringify(se.functionCall.args??{}),providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("inlineData"in se){let Ue=se.thought===!0,De=!!se.thoughtSignature;je.push({type:Ue?"reasoning-file":"file",data:{type:"data",data:se.inlineData.data},mediaType:se.inlineData.mimeType,providerMetadata:De?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("toolCall"in se&&se.toolCall){let Ue=se.toolCall.id||w.generateId();be=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:`server:${se.toolCall.toolType}`,input:JSON.stringify(se.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolCall.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolCall.toolType})})}else if("toolResponse"in se&&se.toolResponse){let Ue=be||se.toolResponse.id||w.generateId();je.push({type:"tool-result",toolCallId:Ue,toolName:`server:${se.toolResponse.toolType}`,result:se.toolResponse.response??{},providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolResponse.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolResponse.toolType})}),be=void 0}let ne=sn({groundingMetadata:ce?.groundingMetadata,generateId:w.generateId})??[];for(let se of ne)je.push(se);return{content:je,finishReason:{unified:Ce?"content-filter":on({finishReason:Ee,hasToolCalls:je.some((se)=>se.type==="tool-call"&&!se.providerExecuted)}),raw:Ee},usage:Jt(ye),warnings:A,providerMetadata:pe({promptFeedback:x.promptFeedback??null,groundingMetadata:ce?.groundingMetadata??null,...V!=null?{groundingMetadataPerRequest:V}:{},urlContextMetadata:ce?.urlContextMetadata??null,safetyRatings:ce?.safetyRatings??null,usageMetadata:ye??null,finishMessage:ce?.finishMessage??null,serviceTier:ye?.serviceTier??null,...ce?.continuationToken!=null?{continuationToken:ce.continuationToken}:{},...ee!=null?{initialPromptTokenCount:ee}:{}}),response:{id:x.responseId??void 0}}}async doGenerate(w){let{args:x,warnings:A,providerOptionsNames:N,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w),V=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),pe=(ne)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:V,body:ne,failedResponseHandler:Xe,successfulResponseHandler:p(In),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:ce,value:Re,rawValue:Le}=await pe(x),Ce=[],Ee=[],je,Ne=Re.usageMetadata?.promptTokenCount,ye=!1;while(!0){let ne=Re.candidates?.[0];Ee.push(ne?.groundingMetadata??null);let se=ne?.finishReason==="CONTINUATION"?ne.continuationToken:void 0;if(je=jt(je,Re.usageMetadata??void 0),se==null)break;Ce.push(...f.convertGenerateContentResponse({config:this.config,response:Re,warnings:A,providerOptionsNames:N,toolNameMapping:re,jsonResponseToolName:ee}).content),ye=!0,{responseHeaders:ce,value:Re,rawValue:Le}=await pe({...x,continuationToken:se})}let ie=f.convertGenerateContentResponse({config:this.config,response:{...Re,usageMetadata:je},warnings:A,providerOptionsNames:N,toolNameMapping:re,jsonResponseToolName:ee,initialPromptTokenCount:ye?Ne:void 0,groundingMetadataPerRequest:ye?Ee:void 0}),be={...ie,content:[...Ce,...ie.content]};return{...be,request:{body:x},response:{...be.response,headers:ce,body:Le}}}async doStream(w){let{args:x,warnings:A,providerOptionsNames:N,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w,{isStreaming:!0}),V=(Be)=>Object.fromEntries(N.map((Pe)=>[Pe,Be])),pe=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),ce=(Be)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:pe,body:Be,failedResponseHandler:Xe,successfulResponseHandler:D(Lo),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:Re,value:Le}=await ce(x),Ce=[],Ee=null,je=to({stream:Le,getContinuationToken:(Be)=>{let Pe=Be.candidates?.[0];if(Pe?.groundingMetadata!=null)Ee=Pe.groundingMetadata;return Pe?.finishReason==="CONTINUATION"?Pe.continuationToken??void 0:void 0},continueStream:async(Be)=>{let{value:Pe}=await ce({...x,continuationToken:Be});return Ce.push(Ee),Ee=null,Pe}}),Ne={unified:"interrupted",raw:void 0},ye=void 0,ie=void 0,be=void 0,ne=null,se=null,Ue=null,De=null,qe=null,We=null,nt,Ke=this.config.generateId,Qe=!1,pt=!1,ze=null,ot=null,Ve=0,at=new Set,rt,dt,Fe=[],et=(Be)=>{let Pe=Fe.pop();if(Pe==null)return;let{finalJSON:ut,closingDelta:st}=Pe.accumulator.finalize();if(st.length>0)Be.enqueue({type:"tool-input-delta",id:Pe.toolCallId,delta:st,providerMetadata:Pe.providerMetadata});Be.enqueue({type:"tool-input-end",id:Pe.toolCallId,providerMetadata:Pe.providerMetadata}),Be.enqueue({type:"tool-call",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:ut,providerMetadata:Pe.providerMetadata}),Qe=!0},Je={stream:je.pipeThrough(new TransformStream({start(Be){Be.enqueue({type:"stream-start",warnings:A})},transform(Be,Pe){if("type"in Be){Ne={unified:"interrupted",raw:void 0};return}if(w.includeRawChunks)Pe.enqueue({type:"raw",rawValue:Be.rawValue});if(!Be.success){if(Ne.unified==="interrupted")Ne={unified:"error",raw:void 0};Pe.enqueue({type:"error",error:Be.error});return}let ut=Be.value;if(ut.error!=null){Ne={unified:"error",raw:void 0};let Ye=ut.error;Pe.enqueue({type:"error",error:xe({message:Ye.message,type:Ye.status,code:Ye.code??void 0,statusCode:Ye.code??void 0,isRetryable:Ye.code!=null&&(Ye.code===408||Ye.code===409||Ye.code===429||Ye.code>=500),data:Ye})});return}if(!pt&&ut.responseId!=null)pt=!0,Pe.enqueue({type:"response-metadata",id:ut.responseId});let st=ut.usageMetadata;if(st!=null)ye=st;if(ut.promptFeedback!=null&&nt==null){if(ne=ut.promptFeedback,an(ut.promptFeedback.blockReason))nt=ut.promptFeedback.blockReason,Ne={unified:"content-filter",raw:nt}}let it=ut.candidates?.[0];if(it!=null){if(it.groundingMetadata!=null)se=it.groundingMetadata;if(it.urlContextMetadata!=null)Ue=it.urlContextMetadata;if(it.safetyRatings!=null)De=it.safetyRatings;if(it.finishMessage!=null)qe=it.finishMessage;if(it.continuationToken!=null)We=it.continuationToken}if(nt!=null||it==null)return;let wt=it.content,St=sn({groundingMetadata:it.groundingMetadata,generateId:Ke});if(St!=null){for(let Ye of St)if(Ye.sourceType==="url"&&!at.has(Ye.url))at.add(Ye.url),Pe.enqueue(Ye)}if(wt!=null){let Ye=wt.parts??[];for(let Ge of Ye)if("executableCode"in Ge&&Ge.executableCode?.code){let $e=Ke();rt=$e,Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),input:JSON.stringify(Ge.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in Ge&&Ge.codeExecutionResult){let $e=rt;if($e)Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),result:{outcome:Ge.codeExecutionResult.outcome,output:Ge.codeExecutionResult.output??""}})}else if("text"in Ge&&Ge.text!=null){let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;if(Ge.text.length===0){if($e!=null&&ze!==null)Pe.enqueue({type:"text-delta",id:ze,delta:"",providerMetadata:$e})}else if(Ge.thought===!0){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot===null)ot=String(Ve++),Pe.enqueue({type:"reasoning-start",id:ot,providerMetadata:$e});Pe.enqueue({type:"reasoning-delta",id:ot,delta:Ge.text,providerMetadata:$e})}else{if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;if(ze===null)ze=String(Ve++),Pe.enqueue({type:"text-start",id:ze,providerMetadata:$e});Pe.enqueue({type:"text-delta",id:ze,delta:Ge.text,providerMetadata:$e})}}else if("inlineData"in Ge){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;let $e=Ge.thought===!0,yt=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;Pe.enqueue({type:$e?"reasoning-file":"file",mediaType:Ge.inlineData.mimeType,data:{type:"data",data:Ge.inlineData.data},providerMetadata:yt})}else if("toolCall"in Ge&&Ge.toolCall){let $e=Ge.toolCall.id||Ke();dt=$e;let yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolCall.toolType});Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:`server:${Ge.toolCall.toolType}`,input:JSON.stringify(Ge.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:yt})}else if("toolResponse"in Ge&&Ge.toolResponse){let $e=dt||Ge.toolResponse.id||Ke(),yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolResponse.toolType});Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:`server:${Ge.toolResponse.toolType}`,result:Ge.toolResponse.response??{},providerMetadata:yt}),dt=void 0}for(let Ge of Ye){if(!("functionCall"in Ge))continue;let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0,yt=Ge.functionCall.partialArgs!=null||Ge.functionCall.name!=null&&Ge.functionCall.willContinue===!0,Hn=Ge.functionCall.name==null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue==null,Vn=Ge.functionCall.name!=null&&Ge.functionCall.args!=null&&Ge.functionCall.partialArgs==null,Wn=Ge.functionCall.name!=null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue!==!0;if(yt){if(Ge.functionCall.name!=null){let ct=Ge.functionCall.id||Ke(),gt=new vo;if(Fe.push({toolCallId:ct,toolName:Ge.functionCall.name,accumulator:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-start",id:ct,toolName:Ge.functionCall.name,providerMetadata:$e}),Ge.functionCall.partialArgs!=null){let ft=Ge.functionCall.partialArgs,{textDelta:It}=gt.processPartialArgs(ft);if(It.length>0)Pe.enqueue({type:"tool-input-delta",id:ct,delta:It,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&ft.every((Kn)=>Kn.willContinue!==!0))et(Pe)}}else if(Ge.functionCall.partialArgs!=null&&Fe.length>0){let ct=Fe[Fe.length-1],gt=Ge.functionCall.partialArgs,{textDelta:ft}=ct.accumulator.processPartialArgs(gt);if(ft.length>0)Pe.enqueue({type:"tool-input-delta",id:ct.toolCallId,delta:ft,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&>.every((It)=>It.willContinue!==!0))et(Pe)}}else if(Hn&&Fe.length>0)et(Pe);else if(Vn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name,ft=typeof Ge.functionCall.args==="string"?Ge.functionCall.args:JSON.stringify(Ge.functionCall.args??{});Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-delta",id:ct,delta:ft,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:ft,providerMetadata:$e}),Qe=!0}else if(Wn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name;Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:"{}",providerMetadata:$e}),Qe=!0}}}if(it.finishReason==="CONTINUATION"){if(ie==null)be=ye?.promptTokenCount;ie=jt(ie,ye),ye=void 0}if(it.finishReason!=null)Ne={unified:on({finishReason:it.finishReason,hasToolCalls:Qe}),raw:it.finishReason}},flush(Be){if(ye=jt(ie,ye),ze!==null)Be.enqueue({type:"text-end",id:ze});if(ot!==null)Be.enqueue({type:"reasoning-end",id:ot});Be.enqueue({type:"finish",finishReason:Ne,usage:Jt(ye),providerMetadata:V({promptFeedback:ne,groundingMetadata:se,...Ce.length>0?{groundingMetadataPerRequest:[...Ce,Ee]}:{},urlContextMetadata:Ue,safetyRatings:De,usageMetadata:ye??null,finishMessage:qe,serviceTier:ye?.serviceTier??null,...We!=null&&(Ne.raw==="MAX_TOKENS"||Ne.raw==="CONTINUATION")?{continuationToken:We}:{},...be!=null?{initialPromptTokenCount:be}:{}})})}})),response:{headers:Re},request:{body:x}};return{...Je,stream:ee==null?Je.stream:Je.stream.pipeThrough(Yt(ee))}}};function ko(){return 65536}function xo(f){let w=f.toLowerCase();if(w.includes("2.5-pro")||w.includes("gemini-3-pro-image"))return 32768;return 24576}function Ro({reasoning:f,modelId:w,warnings:x}){if(!W(f))return;if(At(w).usesGemini3Features&&!w.includes("gemini-3-pro-image"))return Oo({reasoning:f,modelId:w,warnings:x});return Eo({reasoning:f,modelId:w,warnings:x})}function Oo({reasoning:f,modelId:w,warnings:x}){let A=Mo(w);if(f==="none")return{thinkingLevel:A};let N=Se({reasoning:f,effortMap:{minimal:A,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:x});if(N==null)return;return{thinkingLevel:N}}function Mo(f){let w=/(?:^|[/.])(gemini-[^/]*)$/i.exec(f)?.[1].toLowerCase();if(w==="gemini-flash-latest")return"low";let x=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(w??"");if(Number(x?.[1])>=3)return"low";let A=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(w??"");if(A==null)return"minimal";let N=Number(A[1]),B=Number(A[2]);return N>3||N===3&&B>=7?"low":"minimal"}function Eo({reasoning:f,modelId:w,warnings:x}){if(f==="none")return{thinkingBudget:0};let A=lt({reasoning:f,maxOutputTokens:ko(),maxReasoningBudget:xo(w),minReasoningBudget:0,warnings:x});if(A==null)return;return{thinkingBudget:A}}function sn({groundingMetadata:f,generateId:w}){if(!f?.groundingChunks)return;let x=[];for(let A of f.groundingChunks)if(A.web!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.web.uri,title:A.web.title??void 0});else if(A.image!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.image.sourceUri,title:A.image.title??void 0});else if(A.retrievedContext!=null){let N=A.retrievedContext.uri,B=A.retrievedContext.fileSearchStore;if(N&&(N.startsWith("http://")||N.startsWith("https://")))x.push({type:"source",sourceType:"url",id:w(),url:N,title:A.retrievedContext.title??void 0});else if(N){let re=A.retrievedContext.title??"Unknown Document",ee="application/octet-stream",V=void 0;if(N.endsWith(".pdf"))ee="application/pdf",V=N.split("/").pop();else if(N.endsWith(".txt"))ee="text/plain",V=N.split("/").pop();else if(N.endsWith(".docx"))ee="application/vnd.openxmlformats-officedocument.wordprocessingml.document",V=N.split("/").pop();else if(N.endsWith(".doc"))ee="application/msword",V=N.split("/").pop();else if(N.match(/\.(md|markdown)$/))ee="text/markdown",V=N.split("/").pop();else V=N.split("/").pop();x.push({type:"source",sourceType:"document",id:w(),mediaType:ee,title:re,filename:V})}else if(B){let re=A.retrievedContext.title??"Unknown Document";x.push({type:"source",sourceType:"document",id:w(),mediaType:"application/octet-stream",title:re,filename:B.split("/").pop()})}}else if(A.maps!=null){if(A.maps.uri)x.push({type:"source",sourceType:"url",id:w(),url:A.maps.uri,title:A.maps.title??void 0})}return x.length>0?x:void 0}var _n=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:r().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:r().nullish(),endIndex:r().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(r()).nullish(),supportChunkIndices:o(r()).nullish(),confidenceScores:o(r()).nullish(),confidenceScore:o(r()).nullish()})).nullish(),retrievalMetadata:l([t({webDynamicRetrievalScore:r()}),t({})]).nullish()}),Ao=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:r().nullish(),boolValue:c().nullish(),nullValue:v().nullish(),willContinue:c().nullish()}),Cn=()=>t({parts:o(l([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:v().nullish(),partialArgs:o(Ao()).nullish(),willContinue:c().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:c().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:c().nullish(),thoughtSignature:e().nullish()})])).nullish()}),Lt=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:r().nullish(),severity:e().nullish(),severityScore:r().nullish(),blocked:c().nullish()}),xt=()=>o(t({modality:e(),tokenCount:r()}).loose()).nullish(),wn=()=>t({cachedContentTokenCount:r().nullish(),thoughtsTokenCount:r().nullish(),promptTokenCount:r().nullish(),candidatesTokenCount:r().nullish(),toolUsePromptTokenCount:r().nullish(),totalTokenCount:r().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:xt(),cacheTokensDetails:xt(),candidatesTokensDetails:xt(),toolUsePromptTokensDetails:xt()}).loose(),Sn=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),In=a(()=>s(t({responseId:e().nullish(),candidates:o(t({content:Cn().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()}))),Lo=a(()=>s(t({error:fn().nullish(),responseId:e().nullish(),candidates:o(t({content:Cn().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()})));function an(f){return f!=null&&f!==""&&f!=="BLOCK_REASON_UNSPECIFIED"&&f!=="BLOCKED_REASON_UNSPECIFIED"}var jo=()=>U({searchTypes:t({webSearch:t({}).optional(),imageSearch:t({}).optional()}).optional(),timeRangeFilter:t({startTime:e(),endTime:e()}).optional()}),Uo=S({id:"google.google_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),kn=a(()=>s(t({googleSearch:jo().optional()}))),No=2147483648,Go=20000000,Do=new Set(["text","reasoning","source","tool-call","tool-result"]);function Po(f){for(let w of f){let x=w.type;if(x!=="text"&&x!=="image")throw new u({functionality:`batch request type: ${x}`,message:`The Google Batch API does not support batch requests with type "${x}".`})}}var Bt=()=>t({code:l([r(),e()]).nullish(),message:e().nullish(),status:e().nullish()}),qo=()=>t({requestCount:l([e(),r()]).nullish(),successfulRequestCount:l([e(),r()]).nullish(),failedRequestCount:l([e(),r()]).nullish(),pendingRequestCount:l([e(),r()]).nullish()}),rn=()=>t({responsesFile:e().nullish(),inlinedResponses:t({inlinedResponses:o(t({metadata:t({key:e()}),response:v().nullish(),error:Bt().nullish()}))}).nullish()}),xn=()=>t({name:e(),metadata:t({state:e().nullish(),createTime:e().nullish(),batchStats:qo().nullish(),output:rn().nullish()}).nullish(),done:c().nullish(),error:Bt().nullish(),response:rn().nullish()}),Nt=a(()=>s(xn())),$o=a(()=>s(t({operations:o(xn()).nullish(),nextPageToken:e().nullish()}))),Fo=a(()=>s(t({}))),Bo=a(()=>s(t({file:t({name:e(),expirationTime:e().nullish()})}))),Ho=a(()=>s(t({key:e(),response:v().nullish(),error:Bt().nullish()}))),Vo=a(()=>s(t({candidates:o(v()).nullish(),promptFeedback:t({blockReason:e().nullish()}).nullish()}))),Wo=class{constructor(f){this.specificationVersion="v4",this.provider=f.provider,this.batchConfig=f.config,this.supportedUrls=f.supportedUrls,this.batchGenerateId=f.config.generateId??C,this.maxLineBytes=f.maxLineBytes}async doStartBatch(f){Po(f.requests);let w=Yo(f.requests),x=[],A=`ai-sdk-batch-${this.batchGenerateId()}`,N=[],B={batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{requests:{requests:N}}}},re=new TextEncoder,ee=re.encode(JSON.stringify(B)).byteLength,V;for(let je of f.requests){let Ne=je.type==="text"?await Ct.prepareRequest({modelId:je.modelId,config:this.batchConfig,options:je.options}):await this.prepareImageRequest(je),ye={request:Ne.args,metadata:{key:je.id}};if(V==null){let ie=re.encode(JSON.stringify(ye)).byteLength,be=ee+ie+(N.length>0?1:0);if(be<Go)N.push(ye),ee=be;else{V=[];for(let ne of N)V.push(JSON.stringify({key:ne.metadata.key,request:ne.request}),`
|
|
6
|
+
`})}if(Ce&&ee!=null){let ye=Array.from(new Set(Ee));ee({type:"other",message:`Replayed ${Ee.length} \`functionCall\` part(s) for a Gemini 3 model without a \`thoughtSignature\` (tools: ${ye.map((ie)=>`\`${ie}\``).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:x.length>0&&!B?{parts:x}:void 0,contents:A}}async function co(f,{abortSignal:w,maxBytes:x,supportedUrls:A={}}){let N=[];for(let B of f){if(B.role==="assistant"){let re=[];for(let ee of B.content)re.push(ee.type==="tool-result"?{...ee,output:await Xt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})}:ee);N.push({...B,content:re});continue}if(B.role==="tool"){let re=[];for(let ee of B.content){if(ee.type!=="tool-result"){re.push(ee);continue}re.push({...ee,output:await Xt(ee.output,{abortSignal:w,maxBytes:x,supportedUrls:A})})}N.push({...B,content:re});continue}N.push(B)}return N}async function Xt(f,{abortSignal:w,maxBytes:x,supportedUrls:A}){if(f.type!=="content")return f;let N=[];for(let B of f.value){if(B.type!=="file"||B.data.type!=="url"){N.push(B);continue}if(Ze({url:B.data.url.toString(),mediaType:B.mediaType,supportedUrls:A})){N.push(B);continue}let re=await Me(B.data.url.toString(),{abortSignal:w,maxBytes:x}),ee=new Uint8Array(await re.arrayBuffer()),V=Te({data:ee,topLevelType:"image"});N.push({...B,data:{type:"data",data:ee},mediaType:V??(re.type&&!K(B.mediaType)?re.type:B.mediaType)})}return{...f,value:N}}function bn(f){let{const:w,properties:x,items:A,additionalProperties:N,anyOf:B,oneOf:re,...ee}=f;return{...ee,...w!==void 0?{enum:[w]}:{},...x!=null?{properties:Qt(x)}:{},...A!=null?{items:Array.isArray(A)?A.map(bt):bt(A)}:{},...N!=null?{additionalProperties:typeof N==="boolean"?N:bt(N)}:{},...B!=null?{anyOf:B.map(bt)}:{},...re!=null?{oneOf:re.map(bt)}:{},...ee.$defs!=null?{$defs:Qt(ee.$defs)}:{}}}function Qt(f){return Object.fromEntries(Object.entries(f).map(([w,x])=>[w,bt(x)]))}function bt(f){return typeof f==="boolean"?f:bn(f)}var Et=a(()=>s(t({responseModalities:o(i(["TEXT","IMAGE","AUDIO"])).optional(),thinkingConfig:t({thinkingBudget:r().optional(),includeThoughts:c().optional(),thinkingLevel:i(["minimal","low","medium","high"]).optional()}).optional(),cachedContent:e().optional(),structuredOutputs:c().optional(),safetySettings:o(t({category:i(["HARM_CATEGORY_UNSPECIFIED","HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT","HARM_CATEGORY_CIVIC_INTEGRITY"]),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"])})).optional(),threshold:i(["HARM_BLOCK_THRESHOLD_UNSPECIFIED","BLOCK_LOW_AND_ABOVE","BLOCK_MEDIUM_AND_ABOVE","BLOCK_ONLY_HIGH","BLOCK_NONE","OFF"]).optional(),audioTimestamp:c().optional(),labels:y(e(),e()).optional(),mediaResolution:i(["MEDIA_RESOLUTION_UNSPECIFIED","MEDIA_RESOLUTION_LOW","MEDIA_RESOLUTION_MEDIUM","MEDIA_RESOLUTION_HIGH"]).optional(),imageConfig:t({aspectRatio:i(["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:i(["1K","2K","4K","512"]).optional(),personGeneration:i(["PERSON_GENERATION_UNSPECIFIED","ALLOW_ALL","ALLOW_ADULT","ALLOW_NONE"]).optional(),prominentPeople:i(["PROMINENT_PEOPLE_UNSPECIFIED","ALLOW_PROMINENT_PEOPLE","BLOCK_PROMINENT_PEOPLE"]).optional(),imageOutputOptions:t({mimeType:i(["image/jpeg","image/png"]).optional(),compressionQuality:r().optional()}).optional()}).optional(),retrievalConfig:t({latLng:t({latitude:r(),longitude:r()}).optional()}).optional(),streamFunctionCallArguments:c().optional(),serviceTier:i(["standard","flex","priority"]).optional(),continuationToken:e().optional(),sharedRequestType:i(["priority","flex","standard"]).optional(),requestType:i(["shared"]).optional()}))),po=/(^|[/.])gemini-1(?:[.-]|$)/i,go=/(^|[/.])gemini-2(?:[.-]|$)/i,ho=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,mo=/(^|[/.])gemini-/i;function fo(f){return po.test(f)||/(^|[/.])gemini-pro(?:-vision)?$/i.test(f)||/(^|[/.])gemini-robotics-er-1\.5(?:[.-]|$)/i.test(f)}function At(f){let w=mo.test(f),x=go.test(f),A=fo(f),N=w&&!(A||x);return{supportsGemini2Tools:w&&!A||f.toLowerCase().includes("nano-banana"),supportsFileSearch:ho.test(f)||N,usesGemini3Features:N}}function yo({tools:f,toolChoice:w,modelId:x,isVertexProvider:A=!1}){f=f?.length?f:void 0;let N=[],{supportsGemini2Tools:B,supportsFileSearch:re,usesGemini3Features:ee}=At(x);if(f==null)return{tools:void 0,toolConfig:void 0,toolWarnings:N};let V=f.some((Ce)=>Ce.type==="function"),pe=f.some((Ce)=>Ce.type==="provider");if(V&&pe&&!ee)N.push({type:"unsupported",feature:"combination of function and provider-defined tools"});if(pe){let Ce=[];if(f.filter((Ee)=>Ee.type==="provider").forEach((Ee)=>{switch(Ee.id){case"google.google_search":if(B)Ce.push({googleSearch:{...Ee.args}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Google Search requires Gemini 2.0 or newer."});break;case"google.enterprise_web_search":if(B)Ce.push({enterpriseWebSearch:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"Enterprise Web Search requires Gemini 2.0 or newer."});break;case"google.url_context":if(B)Ce.push({urlContext:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The URL context tool is not supported with other Gemini models than Gemini 2."});break;case"google.code_execution":if(B)Ce.push({codeExecution:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The code execution tool is not supported with other Gemini models than Gemini 2."});break;case"google.file_search":if(re)Ce.push({fileSearch:{...Ee.args}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The file search tool is only supported with Gemini 2.5 models and Gemini 3 models."});break;case"google.vertex_rag_store":if(B)Ce.push({retrieval:{vertex_rag_store:{rag_resources:{rag_corpus:Ee.args.ragCorpus},similarity_top_k:Ee.args.topK}}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The RAG store tool is not supported with other Gemini models than Gemini 2."});break;case"google.google_maps":if(B)Ce.push({googleMaps:{}});else N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`,details:"The Google Maps grounding tool is not supported with Gemini models other than Gemini 2 or newer."});break;default:N.push({type:"unsupported",feature:`provider-defined tool ${Ee.id}`})}}),V&&ee&&Ce.length>0){let Ee=[];for(let Ne of f)if(Ne.type==="function")Ee.push(Zt(Ne));let je={functionCallingConfig:{mode:"VALIDATED"},...!A&&{includeServerSideToolInvocations:!0}};if(w!=null)switch(w.type){case"auto":break;case"none":je.functionCallingConfig={mode:"NONE"};break;case"required":je.functionCallingConfig={mode:"ANY"};break;case"tool":je.functionCallingConfig={mode:"ANY",allowedFunctionNames:[w.toolName]}}return{tools:[...Ce,{functionDeclarations:Ee}],toolConfig:je,toolWarnings:N}}return{tools:Ce.length>0?Ce:void 0,toolConfig:void 0,toolWarnings:N}}let ce=[],Re=!1;for(let Ce of f)switch(Ce.type){case"function":if(ce.push(Zt(Ce)),Ce.strict===!0)Re=!0;break;default:N.push({type:"unsupported",feature:`function tool ${Ce.name}`})}if(w==null)return{tools:[{functionDeclarations:ce}],toolConfig:Re?{functionCallingConfig:{mode:"VALIDATED"}}:void 0,toolWarnings:N};let Le=w.type;switch(Le){case"auto":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:Re?"VALIDATED":"AUTO"}},toolWarnings:N};case"none":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:N};case"required":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:N};case"tool":return{tools:[{functionDeclarations:ce}],toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[w.toolName]}},toolWarnings:N};default:throw new u({functionality:`tool choice type: ${Le}`})}}function Zt(f){return{name:f.name,description:f.description??"",parametersJsonSchema:f.inputSchema}}var vo=class{constructor(){this.accumulatedArgs={},this.jsonText="",this.pathStack=[],this.stringOpen=!1}processPartialArgs(f){let w="";for(let x of f){let A=x.jsonPath.endsWith("[]"),N=(A?x.jsonPath.slice(0,-2):x.jsonPath).replace(/^\$\./,"");if(!N||N==="$")continue;let B=bo(N),re=_o(this.accumulatedArgs,B);if(x.stringValue!=null&&re!==void 0){let V=JSON.stringify(x.stringValue).slice(1,-1);Ut(this.accumulatedArgs,B,re+x.stringValue),w+=V;continue}let ee=Co(x);if(ee==null){if(re!==void 0||x.willContinue===!0)continue;Ut(this.accumulatedArgs,B,A?[]:{}),w+=this.emitContainer(B,A);continue}Ut(this.accumulatedArgs,B,ee.value),w+=this.emitNavigationTo(B,x,ee.json)}return this.jsonText+=w,{currentJSON:this.accumulatedArgs,textDelta:w}}finalize(){let f=JSON.stringify(this.accumulatedArgs);return{finalJSON:f,closingDelta:f.slice(this.jsonText.length)}}ensureRoot(){if(this.pathStack.length===0)return this.pathStack.push({segment:"",isArray:!1,childCount:0}),"{";return""}emitNavigationTo(f,w,x){let A="";if(this.stringOpen)A+='"',this.stringOpen=!1;A+=this.ensureRoot();let N=f.slice(0,-1),B=f[f.length-1],re=this.findCommonStackDepth(N);return A+=this.closeDownTo(re),A+=this.openDownTo(N,B),A+=this.emitLeaf(B,w,x),A}emitContainer(f,w){let x="";if(this.stringOpen)x+='"',this.stringOpen=!1;x+=this.ensureRoot();let A=this.findCommonStackDepth(f);return x+=this.closeDownTo(A),x+=this.openDownTo(f,w?0:""),x}findCommonStackDepth(f){let w=Math.min(this.pathStack.length-1,f.length),x=0;for(let A=0;A<w;A++)if(this.pathStack[A+1].segment===f[A])x++;else break;return x+1}closeDownTo(f){let w="";while(this.pathStack.length>f){let x=this.pathStack.pop();w+=x.isArray?"]":"}"}return w}openDownTo(f,w){let x="",A=this.pathStack.length-1;for(let N=A;N<f.length;N++){let B=f[N],re=this.pathStack[this.pathStack.length-1];if(re.childCount>0)x+=",";if(re.childCount++,typeof B==="string")x+=`${JSON.stringify(B)}:`;let ee=typeof(N+1<f.length?f[N+1]:w)==="number";x+=ee?"[":"{",this.pathStack.push({segment:B,isArray:ee,childCount:0})}return x}emitLeaf(f,w,x){let A="",N=this.pathStack[this.pathStack.length-1];if(N.childCount>0)A+=",";if(N.childCount++,typeof f==="string")A+=`${JSON.stringify(f)}:`;if(w.stringValue!=null&&w.willContinue)A+=x.slice(0,-1),this.stringOpen=!0;else A+=x;return A}};function bo(f){let w=[];for(let x of f.split(".")){let A=x.indexOf("[");if(A===-1)w.push(x);else{if(A>0)w.push(x.slice(0,A));for(let N of x.matchAll(/\[(\d+)\]/g))w.push(parseInt(N[1],10))}}return w}var To=Object.prototype.hasOwnProperty;function Tn(f,w){return To.call(f,w)}function tn(f,w,x){Object.defineProperty(f,w,{value:x,enumerable:!0,configurable:!0,writable:!0})}function _o(f,w){let x=f;for(let A of w){if(x==null||typeof x!=="object")return;let N=x;if(!Tn(N,A))return;x=N[A]}return x}function Ut(f,w,x){let A=f;for(let N=0;N<w.length-1;N++){let B=w[N],re=w[N+1];if(!Tn(A,B)||A[B]==null)tn(A,B,typeof re==="number"?[]:{});A=A[B]}tn(A,w[w.length-1],x)}function Co(f){let w=f.stringValue??f.numberValue??f.boolValue;if(w!=null)return{value:w,json:JSON.stringify(w)};if("nullValue"in f)return{value:null,json:"null"}}function nn({finishReason:f,hasToolCalls:w}){switch(f){case"STOP":return w?"tool-calls":"stop";case"MAX_TOKENS":case"CONTINUATION":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 wo=["HARM_CATEGORY_HATE_SPEECH","HARM_CATEGORY_DANGEROUS_CONTENT","HARM_CATEGORY_HARASSMENT","HARM_CATEGORY_SEXUALLY_EXPLICIT"],So=/(^|[/.])gemini-2\.5(?:[.-]|$)/i,Io={"image/png":[/^gs:\/\/.*$/],"image/jpeg":[/^gs:\/\/.*$/],"image/webp":[/^gs:\/\/.*$/],"application/pdf":[/^gs:\/\/.*$/],"text/plain":[/^gs:\/\/.*$/]},Ct=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}constructor(w,x){this.specificationVersion="v4",this.modelId=w,this.config=x,this.generateId=x.generateId??C}get provider(){return this.config.provider}get supportedUrls(){return this.config.supportedUrls?.()??{}}static async prepareRequest({modelId:w,config:x,options:{prompt:A,maxOutputTokens:N,temperature:B,topP:re,topK:ee,frequencyPenalty:V,presencePenalty:pe,stopSequences:ce,responseFormat:Re,seed:Le,tools:Ce,toolChoice:Ee,reasoning:je,providerOptions:Ne,abortSignal:ye},isStreaming:ie=!1}){let be=[],ne=x.provider.includes("vertex")?["googleVertex","vertex"]:["google"],se;for(let st of ne)if(se=await h({provider:st,providerOptions:Ne,schema:Et}),se!=null)break;if(se==null&&!ne.includes("google"))se=await h({provider:"google",providerOptions:Ne,schema:Et});let Ue=x.provider.startsWith("google.vertex.");if(Ce?.some((st)=>st.type==="provider"&&st.id==="google.vertex_rag_store")&&!Ue)be.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 (${x.provider}).`});if(se?.streamFunctionCallArguments&&!Ue)be.push({type:"other",message:`'streamFunctionCallArguments' is only supported on the Vertex AI API and will be ignored with the current Google provider (${x.provider}). See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling#streaming-fc`});if(se?.serviceTier&&Ue)be.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"});if((se?.sharedRequestType||se?.requestType)&&!Ue)be.push({type:"other",message:`'sharedRequestType' and 'requestType' are Vertex AI options and are ignored with the current Google provider (${x.provider}).`});let De=Ue&&(se?.sharedRequestType||se?.requestType)?{...se.sharedRequestType&&{"X-Vertex-AI-LLM-Shared-Request-Type":se.sharedRequestType},...se.requestType&&{"X-Vertex-AI-LLM-Request-Type":se.requestType}}:void 0,qe=Ue?void 0:se?.serviceTier,We=se?.imageConfig;if(We!=null&&!Ue){let{personGeneration:st,prominentPeople:it,imageOutputOptions:wt,...St}=We,Ye=Object.entries({personGeneration:st,prominentPeople:it,imageOutputOptions:wt}).filter(([,Ge])=>Ge!=null).map(([Ge])=>`'imageConfig.${Ge}'`);if(Ye.length>0)be.push({type:"other",message:`${Ye.join(", ")} ${Ye.length===1?"is a Vertex AI option and is":"are Vertex AI options and are"} ignored with the current Google provider (${x.provider}).`}),We=St}let nt=w.toLowerCase().startsWith("gemma-"),Ke=!Ue&&So.test(w);if(Ke&&V!=null)be.push({type:"unsupported",feature:"frequencyPenalty"});if(Ke&&pe!=null)be.push({type:"unsupported",feature:"presencePenalty"});let{usesGemini3Features:Qe}=At(w),pt=Qe&&x.downloadToolResultFiles?.supportsGoogleCloudStorageUrls?Io:void 0,{contents:ze,systemInstruction:ot}=uo(x.downloadToolResultFiles?await co(A,{abortSignal:ye,maxBytes:x.downloadToolResultFiles.maxBytes,supportedUrls:pt}):A,{isGemmaModel:nt,isGemini3Model:Qe,onWarning:(st)=>be.push(st),providerOptionsNames:ne,supportsFunctionResponseParts:Qe,includeFunctionCallIds:!Ue,supportedFunctionResponseUrls:pt}),{tools:Ve,toolConfig:at,toolWarnings:rt}=yo({tools:Ce,toolChoice:Ee,modelId:w,isVertexProvider:Ue}),dt=le({tools:Ce,providerToolNames:{"google.code_execution":"code_execution"}}),Fe=se?.thinkingConfig?.thinkingBudget!=null||se?.thinkingConfig?.thinkingLevel!=null?void 0:Ro({reasoning:je,modelId:w,warnings:be}),et=se?.thinkingConfig||Fe?{...Fe,...se?.thinkingConfig}:void 0,Je=ie&&Ue?se?.streamFunctionCallArguments??!1:void 0,Be=se?.threshold,Pe=se?.safetySettings??(Be!=null?wo.map((st)=>({category:st,threshold:Be})):void 0),ut=at||Je||se?.retrievalConfig?{...at,...Je&&{functionCallingConfig:{...at?.functionCallingConfig,streamFunctionCallArguments:!0}},...se?.retrievalConfig&&{retrievalConfig:se.retrievalConfig}}:void 0;return{args:{generationConfig:{maxOutputTokens:N,temperature:B,topK:ee,topP:re,frequencyPenalty:Ke?void 0:V,presencePenalty:Ke?void 0:pe,stopSequences:ce,seed:Le,responseMimeType:Re?.type==="json"?"application/json":void 0,responseJsonSchema:Re?.type==="json"&&Re.schema!=null&&(se?.structuredOutputs??!0)?bn(Re.schema):void 0,...se?.audioTimestamp&&{audioTimestamp:se.audioTimestamp},responseModalities:se?.responseModalities,thinkingConfig:et,...se?.mediaResolution&&{mediaResolution:se.mediaResolution},...We&&{imageConfig:We}},contents:ze,systemInstruction:nt?void 0:ot,safetySettings:Pe,tools:Ve,toolConfig:ut,cachedContent:se?.cachedContent,labels:se?.labels,serviceTier:qe,...se?.continuationToken!=null&&{continuationToken:se.continuationToken}},warnings:[...be,...rt],providerOptionsNames:ne,extraHeaders:De,toolNameMapping:dt}}async getArgs(w,{isStreaming:x=!1}={}){let{responseFormat:A,tools:N,toolChoice:B}=w,re;if(A?.type==="json"&&A.schema!=null&&N?.some((ee)=>ee.type==="function")&&/(^|\/)gemini-/i.test(this.modelId)&&(!At(this.modelId).usesGemini3Features||B?.type==="required"||B?.type==="tool")){let ee="json";for(let V=1;N.some((pe)=>pe.name===ee);V++)ee=`json_${V}`;re={type:"function",name:ee,description:A.description??"Respond with a JSON object.",inputSchema:A.schema}}return{...await f.prepareRequest({modelId:this.modelId,config:this.config,options:re==null?w:{...w,responseFormat:void 0,tools:[...N??[],re],toolChoice:B?.type==="tool"?B:B?.type==="none"?{type:"tool",toolName:re.name}:{type:"required"}},isStreaming:x}),jsonResponseToolName:re?.name}}static convertGenerateContentResponse({config:w,response:x,warnings:A,providerOptionsNames:N,toolNameMapping:B,jsonResponseToolName:re,initialPromptTokenCount:ee,groundingMetadataPerRequest:V}){let pe=(se)=>Object.fromEntries(N.map((Ue)=>[Ue,se])),ce=x.candidates?.[0],Re=x.promptFeedback?.blockReason,Le=sn(Re)?Re:void 0,Ce=ce?.finishReason==null&&Le!=null,Ee=ce?.finishReason??Le,je=[],Ne=ce?.content?.parts??[],ye=x.usageMetadata,ie,be;for(let se of Ne)if("executableCode"in se&&se.executableCode?.code){let Ue=w.generateId();ie=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:B?.toCustomToolName("code_execution")??"code_execution",input:JSON.stringify(se.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in se&&se.codeExecutionResult)je.push({type:"tool-result",toolCallId:ie,toolName:B?.toCustomToolName("code_execution")??"code_execution",result:{outcome:se.codeExecutionResult.outcome,output:se.codeExecutionResult.output??""}});else if("text"in se&&se.text!=null){if(re!=null&&se.thought!==!0)continue;let Ue=se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0;if(se.text.length===0){if(Ue!=null&&je.length>0){let De=je[je.length-1];De.providerMetadata=Ue}}else je.push({type:se.thought===!0?"reasoning":"text",text:se.text,providerMetadata:Ue})}else if("functionCall"in se&&se.functionCall.name!=null){if(se.functionCall.name===re){je.push({type:"text",text:typeof se.functionCall.args==="string"?se.functionCall.args:JSON.stringify(se.functionCall.args??{}),...se.thoughtSignature?{providerMetadata:pe({thoughtSignature:se.thoughtSignature})}:{}});continue}je.push({type:"tool-call",toolCallId:se.functionCall.id||w.generateId(),toolName:se.functionCall.name,input:JSON.stringify(se.functionCall.args??{}),providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("inlineData"in se){let Ue=se.thought===!0,De=!!se.thoughtSignature;je.push({type:Ue?"reasoning-file":"file",data:{type:"data",data:se.inlineData.data},mediaType:se.inlineData.mimeType,providerMetadata:De?pe({thoughtSignature:se.thoughtSignature}):void 0})}else if("toolCall"in se&&se.toolCall){let Ue=se.toolCall.id||w.generateId();be=Ue,je.push({type:"tool-call",toolCallId:Ue,toolName:`server:${se.toolCall.toolType}`,input:JSON.stringify(se.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolCall.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolCall.toolType})})}else if("toolResponse"in se&&se.toolResponse){let Ue=be||se.toolResponse.id||w.generateId();je.push({type:"tool-result",toolCallId:Ue,toolName:`server:${se.toolResponse.toolType}`,result:se.toolResponse.response??{},providerMetadata:se.thoughtSignature?pe({thoughtSignature:se.thoughtSignature,serverToolCallId:Ue,serverToolType:se.toolResponse.toolType}):pe({serverToolCallId:Ue,serverToolType:se.toolResponse.toolType})}),be=void 0}let ne=on({groundingMetadata:ce?.groundingMetadata,generateId:w.generateId})??[];for(let se of ne)je.push(se);return{content:je,finishReason:{unified:Ce?"content-filter":nn({finishReason:Ee,hasToolCalls:je.some((se)=>se.type==="tool-call"&&!se.providerExecuted)}),raw:Ee},usage:Jt(ye),warnings:A,providerMetadata:pe({promptFeedback:x.promptFeedback??null,groundingMetadata:ce?.groundingMetadata??null,...V!=null?{groundingMetadataPerRequest:V}:{},urlContextMetadata:ce?.urlContextMetadata??null,safetyRatings:ce?.safetyRatings??null,usageMetadata:ye??null,finishMessage:ce?.finishMessage??null,serviceTier:ye?.serviceTier??null,...ce?.continuationToken!=null?{continuationToken:ce.continuationToken}:{},...ee!=null?{initialPromptTokenCount:ee}:{}}),response:{id:x.responseId??void 0}}}async doGenerate(w){let{args:x,warnings:A,providerOptionsNames:N,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w),V=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),pe=(ne)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:generateContent`,headers:V,body:ne,failedResponseHandler:Xe,successfulResponseHandler:p(In),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:ce,value:Re,rawValue:Le}=await pe(x),Ce=[],Ee=[],je,Ne=Re.usageMetadata?.promptTokenCount,ye=!1;while(!0){let ne=Re.candidates?.[0];Ee.push(ne?.groundingMetadata??null);let se=ne?.finishReason==="CONTINUATION"?ne.continuationToken:void 0;if(je=jt(je,Re.usageMetadata??void 0),se==null)break;Ce.push(...f.convertGenerateContentResponse({config:this.config,response:Re,warnings:A,providerOptionsNames:N,toolNameMapping:re,jsonResponseToolName:ee}).content),ye=!0,{responseHeaders:ce,value:Re,rawValue:Le}=await pe({...x,continuationToken:se})}let ie=f.convertGenerateContentResponse({config:this.config,response:{...Re,usageMetadata:je},warnings:A,providerOptionsNames:N,toolNameMapping:re,jsonResponseToolName:ee,initialPromptTokenCount:ye?Ne:void 0,groundingMetadataPerRequest:ye?Ee:void 0}),be={...ie,content:[...Ce,...ie.content]};return{...be,request:{body:x},response:{...be.response,headers:ce,body:Le}}}async doStream(w){let{args:x,warnings:A,providerOptionsNames:N,extraHeaders:B,toolNameMapping:re,jsonResponseToolName:ee}=await this.getArgs(w,{isStreaming:!0}),V=(Be)=>Object.fromEntries(N.map((Pe)=>[Pe,Be])),pe=d(this.config.headers?await _(this.config.headers):void 0,w.headers,B),ce=(Be)=>g({url:`${this.config.baseURL}/${Tt(this.modelId)}:streamGenerateContent?alt=sse`,headers:pe,body:Be,failedResponseHandler:Xe,successfulResponseHandler:D(Lo),abortSignal:w.abortSignal,fetch:this.config.fetch}),{responseHeaders:Re,value:Le}=await ce(x),Ce=[],Ee=null,je=to({stream:Le,getContinuationToken:(Be)=>{let Pe=Be.candidates?.[0];if(Pe?.groundingMetadata!=null)Ee=Pe.groundingMetadata;return Pe?.finishReason==="CONTINUATION"?Pe.continuationToken??void 0:void 0},continueStream:async(Be)=>{let{value:Pe}=await ce({...x,continuationToken:Be});return Ce.push(Ee),Ee=null,Pe}}),Ne={unified:"interrupted",raw:void 0},ye=void 0,ie=void 0,be=void 0,ne=null,se=null,Ue=null,De=null,qe=null,We=null,nt,Ke=this.config.generateId,Qe=!1,pt=!1,ze=null,ot=null,Ve=0,at=new Set,rt,dt,Fe=[],et=(Be)=>{let Pe=Fe.pop();if(Pe==null)return;let{finalJSON:ut,closingDelta:st}=Pe.accumulator.finalize();if(st.length>0)Be.enqueue({type:"tool-input-delta",id:Pe.toolCallId,delta:st,providerMetadata:Pe.providerMetadata});Be.enqueue({type:"tool-input-end",id:Pe.toolCallId,providerMetadata:Pe.providerMetadata}),Be.enqueue({type:"tool-call",toolCallId:Pe.toolCallId,toolName:Pe.toolName,input:ut,providerMetadata:Pe.providerMetadata}),Qe=!0},Je={stream:je.pipeThrough(new TransformStream({start(Be){Be.enqueue({type:"stream-start",warnings:A})},transform(Be,Pe){if("type"in Be){Ne={unified:"interrupted",raw:void 0};return}if(w.includeRawChunks)Pe.enqueue({type:"raw",rawValue:Be.rawValue});if(!Be.success){if(Ne.unified==="interrupted")Ne={unified:"error",raw:void 0};Pe.enqueue({type:"error",error:Be.error});return}let ut=Be.value;if(ut.error!=null){Ne={unified:"error",raw:void 0};let Ye=ut.error;Pe.enqueue({type:"error",error:xe({message:Ye.message,type:Ye.status,code:Ye.code??void 0,statusCode:Ye.code??void 0,isRetryable:Ye.code!=null&&(Ye.code===408||Ye.code===409||Ye.code===429||Ye.code>=500),data:Ye})});return}if(!pt&&ut.responseId!=null)pt=!0,Pe.enqueue({type:"response-metadata",id:ut.responseId});let st=ut.usageMetadata;if(st!=null)ye=st;if(ut.promptFeedback!=null&&nt==null){if(ne=ut.promptFeedback,sn(ut.promptFeedback.blockReason))nt=ut.promptFeedback.blockReason,Ne={unified:"content-filter",raw:nt}}let it=ut.candidates?.[0];if(it!=null){if(it.groundingMetadata!=null)se=it.groundingMetadata;if(it.urlContextMetadata!=null)Ue=it.urlContextMetadata;if(it.safetyRatings!=null)De=it.safetyRatings;if(it.finishMessage!=null)qe=it.finishMessage;if(it.continuationToken!=null)We=it.continuationToken}if(nt!=null||it==null)return;let wt=it.content,St=on({groundingMetadata:it.groundingMetadata,generateId:Ke});if(St!=null){for(let Ye of St)if(Ye.sourceType==="url"&&!at.has(Ye.url))at.add(Ye.url),Pe.enqueue(Ye)}if(wt!=null){let Ye=wt.parts??[];for(let Ge of Ye)if("executableCode"in Ge&&Ge.executableCode?.code){let $e=Ke();rt=$e,Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),input:JSON.stringify(Ge.executableCode),providerExecuted:!0})}else if("codeExecutionResult"in Ge&&Ge.codeExecutionResult){let $e=rt;if($e)Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:re.toCustomToolName("code_execution"),result:{outcome:Ge.codeExecutionResult.outcome,output:Ge.codeExecutionResult.output??""}})}else if("text"in Ge&&Ge.text!=null){let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;if(Ge.text.length===0){if($e!=null&&ze!==null)Pe.enqueue({type:"text-delta",id:ze,delta:"",providerMetadata:$e})}else if(Ge.thought===!0){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot===null)ot=String(Ve++),Pe.enqueue({type:"reasoning-start",id:ot,providerMetadata:$e});Pe.enqueue({type:"reasoning-delta",id:ot,delta:Ge.text,providerMetadata:$e})}else{if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;if(ze===null)ze=String(Ve++),Pe.enqueue({type:"text-start",id:ze,providerMetadata:$e});Pe.enqueue({type:"text-delta",id:ze,delta:Ge.text,providerMetadata:$e})}}else if("inlineData"in Ge){if(ze!==null)Pe.enqueue({type:"text-end",id:ze}),ze=null;if(ot!==null)Pe.enqueue({type:"reasoning-end",id:ot}),ot=null;let $e=Ge.thought===!0,yt=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0;Pe.enqueue({type:$e?"reasoning-file":"file",mediaType:Ge.inlineData.mimeType,data:{type:"data",data:Ge.inlineData.data},providerMetadata:yt})}else if("toolCall"in Ge&&Ge.toolCall){let $e=Ge.toolCall.id||Ke();dt=$e;let yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolCall.toolType});Pe.enqueue({type:"tool-call",toolCallId:$e,toolName:`server:${Ge.toolCall.toolType}`,input:JSON.stringify(Ge.toolCall.args??{}),providerExecuted:!0,dynamic:!0,providerMetadata:yt})}else if("toolResponse"in Ge&&Ge.toolResponse){let $e=dt||Ge.toolResponse.id||Ke(),yt=V({...Ge.thoughtSignature?{thoughtSignature:Ge.thoughtSignature}:{},serverToolCallId:$e,serverToolType:Ge.toolResponse.toolType});Pe.enqueue({type:"tool-result",toolCallId:$e,toolName:`server:${Ge.toolResponse.toolType}`,result:Ge.toolResponse.response??{},providerMetadata:yt}),dt=void 0}for(let Ge of Ye){if(!("functionCall"in Ge))continue;let $e=Ge.thoughtSignature?V({thoughtSignature:Ge.thoughtSignature}):void 0,yt=Ge.functionCall.partialArgs!=null||Ge.functionCall.name!=null&&Ge.functionCall.willContinue===!0,Hn=Ge.functionCall.name==null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue==null,Vn=Ge.functionCall.name!=null&&Ge.functionCall.args!=null&&Ge.functionCall.partialArgs==null,Wn=Ge.functionCall.name!=null&&Ge.functionCall.args==null&&Ge.functionCall.partialArgs==null&&Ge.functionCall.willContinue!==!0;if(yt){if(Ge.functionCall.name!=null){let ct=Ge.functionCall.id||Ke(),gt=new vo;if(Fe.push({toolCallId:ct,toolName:Ge.functionCall.name,accumulator:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-start",id:ct,toolName:Ge.functionCall.name,providerMetadata:$e}),Ge.functionCall.partialArgs!=null){let ft=Ge.functionCall.partialArgs,{textDelta:It}=gt.processPartialArgs(ft);if(It.length>0)Pe.enqueue({type:"tool-input-delta",id:ct,delta:It,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&&ft.every((Kn)=>Kn.willContinue!==!0))et(Pe)}}else if(Ge.functionCall.partialArgs!=null&&Fe.length>0){let ct=Fe[Fe.length-1],gt=Ge.functionCall.partialArgs,{textDelta:ft}=ct.accumulator.processPartialArgs(gt);if(ft.length>0)Pe.enqueue({type:"tool-input-delta",id:ct.toolCallId,delta:ft,providerMetadata:$e});if(Ge.functionCall.willContinue!==!0&>.every((It)=>It.willContinue!==!0))et(Pe)}}else if(Hn&&Fe.length>0)et(Pe);else if(Vn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name,ft=typeof Ge.functionCall.args==="string"?Ge.functionCall.args:JSON.stringify(Ge.functionCall.args??{});Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-delta",id:ct,delta:ft,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:ft,providerMetadata:$e}),Qe=!0}else if(Wn){let ct=Ge.functionCall.id||Ke(),gt=Ge.functionCall.name;Pe.enqueue({type:"tool-input-start",id:ct,toolName:gt,providerMetadata:$e}),Pe.enqueue({type:"tool-input-end",id:ct,providerMetadata:$e}),Pe.enqueue({type:"tool-call",toolCallId:ct,toolName:gt,input:"{}",providerMetadata:$e}),Qe=!0}}}if(it.finishReason==="CONTINUATION"){if(ie==null)be=ye?.promptTokenCount;ie=jt(ie,ye),ye=void 0}if(it.finishReason!=null)Ne={unified:nn({finishReason:it.finishReason,hasToolCalls:Qe}),raw:it.finishReason}},flush(Be){if(ye=jt(ie,ye),ze!==null)Be.enqueue({type:"text-end",id:ze});if(ot!==null)Be.enqueue({type:"reasoning-end",id:ot});Be.enqueue({type:"finish",finishReason:Ne,usage:Jt(ye),providerMetadata:V({promptFeedback:ne,groundingMetadata:se,...Ce.length>0?{groundingMetadataPerRequest:[...Ce,Ee]}:{},urlContextMetadata:Ue,safetyRatings:De,usageMetadata:ye??null,finishMessage:qe,serviceTier:ye?.serviceTier??null,...We!=null&&(Ne.raw==="MAX_TOKENS"||Ne.raw==="CONTINUATION")?{continuationToken:We}:{},...be!=null?{initialPromptTokenCount:be}:{}})})}})),response:{headers:Re},request:{body:x}};return{...Je,stream:ee==null?Je.stream:Je.stream.pipeThrough(en(ee))}}};function ko(){return 65536}function xo(f){let w=f.toLowerCase();if(w.includes("2.5-pro")||w.includes("gemini-3-pro-image"))return 32768;return 24576}function Ro({reasoning:f,modelId:w,warnings:x}){if(!W(f))return;if(At(w).usesGemini3Features&&!w.includes("gemini-3-pro-image"))return Oo({reasoning:f,modelId:w,warnings:x});return Eo({reasoning:f,modelId:w,warnings:x})}function Oo({reasoning:f,modelId:w,warnings:x}){let A=Mo(w);if(f==="none")return{thinkingLevel:A};let N=Se({reasoning:f,effortMap:{minimal:A,low:"low",medium:"medium",high:"high",xhigh:"high",max:"high"},warnings:x});if(N==null)return;return{thinkingLevel:N}}function Mo(f){let w=/(?:^|[/.])(gemini-[^/]*)$/i.exec(f)?.[1].toLowerCase();if(w==="gemini-flash-latest")return"low";let x=/^gemini-(\d+)(?:\.\d+)?-pro(?:$|-)/.exec(w??"");if(Number(x?.[1])>=3)return"low";let A=/^gemini-(\d+)\.(\d+)-flash(?:$|-(?!lite(?:-|$)))/.exec(w??"");if(A==null)return"minimal";let N=Number(A[1]),B=Number(A[2]);return N>3||N===3&&B>=7?"low":"minimal"}function Eo({reasoning:f,modelId:w,warnings:x}){if(f==="none")return{thinkingBudget:0};let A=lt({reasoning:f,maxOutputTokens:ko(),maxReasoningBudget:xo(w),minReasoningBudget:0,warnings:x});if(A==null)return;return{thinkingBudget:A}}function on({groundingMetadata:f,generateId:w}){if(!f?.groundingChunks)return;let x=[];for(let A of f.groundingChunks)if(A.web!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.web.uri,title:A.web.title??void 0});else if(A.image!=null)x.push({type:"source",sourceType:"url",id:w(),url:A.image.sourceUri,title:A.image.title??void 0});else if(A.retrievedContext!=null){let N=A.retrievedContext.uri,B=A.retrievedContext.fileSearchStore;if(N&&(N.startsWith("http://")||N.startsWith("https://")))x.push({type:"source",sourceType:"url",id:w(),url:N,title:A.retrievedContext.title??void 0});else if(N){let re=A.retrievedContext.title??"Unknown Document",ee="application/octet-stream",V=void 0;if(N.endsWith(".pdf"))ee="application/pdf",V=N.split("/").pop();else if(N.endsWith(".txt"))ee="text/plain",V=N.split("/").pop();else if(N.endsWith(".docx"))ee="application/vnd.openxmlformats-officedocument.wordprocessingml.document",V=N.split("/").pop();else if(N.endsWith(".doc"))ee="application/msword",V=N.split("/").pop();else if(N.match(/\.(md|markdown)$/))ee="text/markdown",V=N.split("/").pop();else V=N.split("/").pop();x.push({type:"source",sourceType:"document",id:w(),mediaType:ee,title:re,filename:V})}else if(B){let re=A.retrievedContext.title??"Unknown Document";x.push({type:"source",sourceType:"document",id:w(),mediaType:"application/octet-stream",title:re,filename:B.split("/").pop()})}}else if(A.maps!=null){if(A.maps.uri)x.push({type:"source",sourceType:"url",id:w(),url:A.maps.uri,title:A.maps.title??void 0})}return x.length>0?x:void 0}var _n=()=>t({webSearchQueries:o(e()).nullish(),imageSearchQueries:o(e()).nullish(),retrievalQueries:o(e()).nullish(),searchEntryPoint:t({renderedContent:e()}).nullish(),groundingChunks:o(t({web:t({uri:e(),title:e().nullish()}).nullish(),image:t({sourceUri:e(),imageUri:e(),title:e().nullish(),domain:e().nullish()}).nullish(),retrievedContext:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),fileSearchStore:e().nullish(),customMetadata:o(t({key:e(),stringValue:e().nullish(),numericValue:r().nullish(),stringListValue:t({values:o(e()).nullish()}).nullish()})).nullish()}).nullish(),maps:t({uri:e().nullish(),title:e().nullish(),text:e().nullish(),placeId:e().nullish()}).nullish()})).nullish(),groundingSupports:o(t({segment:t({startIndex:r().nullish(),endIndex:r().nullish(),text:e().nullish()}).nullish(),segment_text:e().nullish(),groundingChunkIndices:o(r()).nullish(),supportChunkIndices:o(r()).nullish(),confidenceScores:o(r()).nullish(),confidenceScore:o(r()).nullish()})).nullish(),retrievalMetadata:l([t({webDynamicRetrievalScore:r()}),t({})]).nullish()}),Ao=()=>t({jsonPath:e(),stringValue:e().nullish(),numberValue:r().nullish(),boolValue:c().nullish(),nullValue:v().nullish(),willContinue:c().nullish()}),Cn=()=>t({parts:o(l([t({functionCall:t({id:e().nullish(),name:e().nullish(),args:v().nullish(),partialArgs:o(Ao()).nullish(),willContinue:c().nullish()}),thoughtSignature:e().nullish()}),t({inlineData:t({mimeType:e(),data:e()}),thought:c().nullish(),thoughtSignature:e().nullish()}),t({toolCall:t({toolType:e(),args:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({toolResponse:t({toolType:e(),response:v().nullish(),id:e()}),thoughtSignature:e().nullish()}),t({executableCode:t({language:e(),code:e()}).nullish(),codeExecutionResult:t({outcome:e(),output:e().nullish()}).nullish(),text:e().nullish(),thought:c().nullish(),thoughtSignature:e().nullish()})])).nullish()}),Lt=()=>t({category:e().nullish(),probability:e().nullish(),probabilityScore:r().nullish(),severity:e().nullish(),severityScore:r().nullish(),blocked:c().nullish()}),xt=()=>o(t({modality:e(),tokenCount:r()}).loose()).nullish(),wn=()=>t({cachedContentTokenCount:r().nullish(),thoughtsTokenCount:r().nullish(),promptTokenCount:r().nullish(),candidatesTokenCount:r().nullish(),toolUsePromptTokenCount:r().nullish(),totalTokenCount:r().nullish(),trafficType:e().nullish(),serviceTier:e().nullish(),promptTokensDetails:xt(),cacheTokensDetails:xt(),candidatesTokensDetails:xt(),toolUsePromptTokensDetails:xt()}).loose(),Sn=()=>t({urlMetadata:o(t({retrievedUrl:e(),urlRetrievalStatus:e()})).nullish()}),In=a(()=>s(t({responseId:e().nullish(),candidates:o(t({content:Cn().nullish().or(t({}).strict()),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()}))),Lo=a(()=>s(t({error:fn().nullish(),responseId:e().nullish(),candidates:o(t({content:Cn().nullish(),finishReason:e().nullish(),finishMessage:e().nullish(),continuationToken:e().nullish(),safetyRatings:o(Lt()).nullish(),groundingMetadata:_n().nullish(),urlContextMetadata:Sn().nullish()})).nullish(),usageMetadata:wn().nullish(),promptFeedback:t({blockReason:e().nullish(),safetyRatings:o(Lt()).nullish()}).nullish()})));function sn(f){return f!=null&&f!==""&&f!=="BLOCK_REASON_UNSPECIFIED"&&f!=="BLOCKED_REASON_UNSPECIFIED"}var jo=()=>U({searchTypes:t({webSearch:t({}).optional(),imageSearch:t({}).optional()}).optional(),timeRangeFilter:t({startTime:e(),endTime:e()}).optional()}),Uo=S({id:"google.google_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),kn=a(()=>s(t({googleSearch:jo().optional()}))),No=2147483648,Go=20000000,Do=new Set(["text","reasoning","source","tool-call","tool-result"]);function Po(f){for(let w of f){let x=w.type;if(x!=="text"&&x!=="image")throw new u({functionality:`batch request type: ${x}`,message:`The Google Batch API does not support batch requests with type "${x}".`})}}var Bt=()=>t({code:l([r(),e()]).nullish(),message:e().nullish(),status:e().nullish()}),qo=()=>t({requestCount:l([e(),r()]).nullish(),successfulRequestCount:l([e(),r()]).nullish(),failedRequestCount:l([e(),r()]).nullish(),pendingRequestCount:l([e(),r()]).nullish()}),an=()=>t({responsesFile:e().nullish(),inlinedResponses:t({inlinedResponses:o(t({metadata:t({key:e()}),response:v().nullish(),error:Bt().nullish()}))}).nullish()}),xn=()=>t({name:e(),metadata:t({state:e().nullish(),createTime:e().nullish(),batchStats:qo().nullish(),output:an().nullish()}).nullish(),done:c().nullish(),error:Bt().nullish(),response:an().nullish()}),Nt=a(()=>s(xn())),$o=a(()=>s(t({operations:o(xn()).nullish(),nextPageToken:e().nullish()}))),Fo=a(()=>s(t({}))),Bo=a(()=>s(t({file:t({name:e(),expirationTime:e().nullish()})}))),Ho=a(()=>s(t({key:e(),response:v().nullish(),error:Bt().nullish()}))),Vo=a(()=>s(t({candidates:o(v()).nullish(),promptFeedback:t({blockReason:e().nullish()}).nullish()}))),Wo=class{constructor(f){this.specificationVersion="v4",this.provider=f.provider,this.batchConfig=f.config,this.supportedUrls=f.supportedUrls,this.batchGenerateId=f.config.generateId??C,this.maxLineBytes=f.maxLineBytes}async doStartBatch(f){Po(f.requests);let w=Yo(f.requests),x=[],A=`ai-sdk-batch-${this.batchGenerateId()}`,N=[],B={batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{requests:{requests:N}}}},re=new TextEncoder,ee=re.encode(JSON.stringify(B)).byteLength,V;for(let je of f.requests){let Ne=je.type==="text"?await Ct.prepareRequest({modelId:je.modelId,config:this.batchConfig,options:je.options}):await this.prepareImageRequest(je),ye={request:Ne.args,metadata:{key:je.id}};if(V==null){let ie=re.encode(JSON.stringify(ye)).byteLength,be=ee+ie+(N.length>0?1:0);if(be<Go)N.push(ye),ee=be;else{V=[];for(let ne of N)V.push(JSON.stringify({key:ne.metadata.key,request:ne.request}),`
|
|
7
7
|
`);N.length=0,V.push(JSON.stringify({key:je.id,request:Ne.args}),`
|
|
8
8
|
`)}}else V.push(JSON.stringify({key:je.id,request:Ne.args}),`
|
|
9
9
|
`);for(let ie of Ne.warnings)x.push({requestId:je.id,warning:ie})}let pe=await this.getHeaders(f.headers),ce=`${this.batchConfig.baseURL}/${Tt(w)}:batchGenerateContent`;if(V==null){let{value:je}=await g({url:ce,headers:pe,body:B,failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:je.name,..._t(je),warnings:x}}let Re=new Blob(V,{type:"application/jsonl"});if(V.length=0,Re.size>No)throw new b({argument:"requests",message:"Google batch input files must not exceed 2 GB."});let{value:Le}=await g({url:`${this.getBaseOrigin()}/upload/v1beta/files`,headers:d(pe,{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(Re.size),"X-Goog-Upload-Header-Content-Type":"application/jsonl"}),body:{file:{display_name:`${A}-input`}},failedResponseHandler:Xe,successfulResponseHandler:Jo,abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ce}=await ve({url:Le,headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize","Content-Type":"application/jsonl"},body:{content:Re,values:{byteLength:Re.size,mediaType:"application/jsonl"}},failedResponseHandler:Xe,successfulResponseHandler:p(Bo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{value:Ee}=await g({url:ce,headers:pe,body:{batch:{displayName:A,...f.webhookUrl!=null&&{webhookConfig:{uris:[f.webhookUrl]}},inputConfig:{fileName:Ce.file.name}}},failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch});return{batchId:Ee.name,..._t(Ee),providerMetadata:{google:{inputFileId:Ce.file.name,...Ce.file.expirationTime!=null?{inputFileExpiresAt:Ce.file.expirationTime}:{}}},warnings:x}}async doGetBatchStatus(f){return _t(await this.retrieveBatch(f))}async doCancelBatch(f){return await g({url:`${this.batchConfig.baseURL}/${f.batchId}:cancel`,headers:await this.getHeaders(f.headers),body:{},failedResponseHandler:Xe,successfulResponseHandler:p(Fo),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch}),{}}async doListBatches(f){let w=new URL(`${this.batchConfig.baseURL}/batches`);if(f.limit!=null)w.searchParams.set("pageSize",String(f.limit));if(f.cursor!=null)w.searchParams.set("pageToken",f.cursor);let{value:x}=await R({url:w.toString(),headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p($o),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return{batches:(x.operations??[]).map((A)=>({batchId:A.name,..._t(A)})),...x.nextPageToken!=null?{nextCursor:x.nextPageToken}:{}}}async doGetBatchResults(f){let w=await this.retrieveBatch(f),x=_t(w);if(x.status==="pending")throw new b({argument:"batchId",message:`Google batch "${f.batchId}" is not complete.`});let A=w.metadata?.output?.inlinedResponses?.inlinedResponses??w.response?.inlinedResponses?.inlinedResponses;if(A!=null)return ae(this.iterateBatchResults(A.map((ee)=>({key:ee.metadata.key,response:ee.response,error:ee.error}))));let N=w.metadata?.output?.responsesFile??w.response?.responsesFile;if(N==null){if(x.status==="completed")throw new P({data:w,message:`Google batch "${f.batchId}" completed without batch output.`});return new ReadableStream({start(ee){ee.close()}})}let B=N.split("/").map((ee)=>encodeURIComponent(ee)).join("/"),{value:re}=await R({url:`${this.getBaseOrigin()}/download/v1beta/${B}:download?alt=media`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:_e(Ho,{maxLineBytes:this.maxLineBytes}),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return ae(this.iterateBatchResults(re))}async retrieveBatch(f){let{value:w}=await R({url:`${this.batchConfig.baseURL}/${f.batchId}`,headers:await this.getHeaders(f.headers),failedResponseHandler:Xe,successfulResponseHandler:p(Nt),abortSignal:f.abortSignal,fetch:this.batchConfig.fetch,validateUrl:!1});return w}async*iterateBatchResults(f){for await(let w of f){if(w.error!=null){let ee=Rn(w.error,"Google batch request failed."),V=w.error.status==="CANCELLED"||String(w.error.code)==="1"?"cancelled":"failed";yield{type:"text",id:w.key,status:V,error:ee};continue}if(w.response==null){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned a batch result without a response or error.",code:"invalid_batch_result"}};continue}let x=await q({value:w.response,schema:Vo});if(x.success&&(x.value.candidates==null||x.value.candidates.length===0)){let ee=x.value.promptFeedback??void 0,V=ee?.blockReason??void 0;yield{type:"text",id:w.key,status:"failed",error:{message:V==null?"Google returned a batch response without any candidates.":`Google blocked the batch request (${V}).`,code:V==null?"invalid_response":"prompt_blocked",...V!=null?{type:V}:{}},...ee!=null?{providerMetadata:{google:{promptFeedback:{blockReason:ee.blockReason??null}}}}:{}};continue}let A=await q({value:w.response,schema:In});if(!A.success){yield{type:"text",id:w.key,status:"failed",error:{message:"Google returned an invalid GenerateContent batch result.",code:"invalid_response"}};continue}let N=Ct.convertGenerateContentResponse({config:this.batchConfig,response:A.value,warnings:[],providerOptionsNames:["google"]}),B=Xo(N);if(B!=null){yield{type:"image",id:w.key,status:"succeeded",result:B};continue}let re=N.content.find((ee)=>!Do.has(ee.type));if(re!=null){yield{type:"text",id:w.key,status:"failed",error:{message:`Google returned a "${re.type}" content block, but that content is not supported in AI SDK text batches.`,code:"unsupported_content"}};continue}yield{type:"text",id:w.key,status:"succeeded",result:N}}}async prepareImageRequest(f){let{prompt:w,n:x,size:A,aspectRatio:N,seed:B,files:re,mask:ee,providerOptions:V}=f.options,pe=[];if(ee!=null)throw new u({functionality:"mask-based image editing in Google batches"});if(x>1)throw new u({functionality:"multiple images per Google batch request"});if(A!=null)pe.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let ce=[];if(w!=null)ce.push({type:"text",text:w});for(let ye of re??[])ce.push(ye.type==="url"?{type:"file",data:{type:"url",url:new URL(ye.url)},mediaType:"image/*"}:{type:"file",data:{type:"data",data:ye.data},mediaType:ye.mediaType});let Re=await h({provider:"google",providerOptions:V,schema:kn}),{responseModalities:Le,imageConfig:Ce,...Ee}=await h({provider:"google",providerOptions:V,schema:Et})??{},je=await h({provider:"google",providerOptions:{google:{...Ee,responseModalities:["IMAGE"],imageConfig:N!=null||Ce!=null?{...Ce,...N!=null?{aspectRatio:N}:{}}:void 0}},schema:Et}),Ne=await Ct.prepareRequest({modelId:f.modelId,config:this.batchConfig,options:{prompt:[{role:"user",content:ce}],seed:B,providerOptions:{google:je??{responseModalities:["IMAGE"]}},tools:Re?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Re.googleSearch}]:void 0}});return{...Ne,warnings:[...pe,...Ne.warnings]}}async getHeaders(f){return d(this.batchConfig.headers?await _(this.batchConfig.headers):void 0,f)}getBaseOrigin(){return this.batchConfig.baseURL.replace(/\/v1beta$/,"")}};function _t(f){let w=f.metadata?.state??void 0,x=zo(f.metadata?.batchStats),A=f.metadata?.createTime??void 0,N=f.error!=null?Rn(f.error,"Google batch failed."):void 0;return{status:Ko({rawStatus:w,done:f.done??void 0,hasError:N!=null}),...w!=null?{rawStatus:w}:{},...x!=null?{requestCounts:x}:{},...N!=null?{error:N}:{},...A!=null?{createdAt:A}:{}}}function Ko({rawStatus:f,done:w,hasError:x}){if(x)return"failed";if(f==null)return w?"completed":"pending";switch(f.replace(/^(?:BATCH|JOB)_STATE_/,"")){case"SUCCEEDED":return"completed";case"FAILED":case"CANCELLED":case"EXPIRED":return"failed";default:return"pending"}}function zo(f){let w=Rt(f?.requestCount),x=Rt(f?.successfulRequestCount??0),A=Rt(f?.failedRequestCount??0),N=Rt(f?.pendingRequestCount??0);return ge({total:w,pending:N,completed:x,failed:A})}function Rt(f){let w=typeof f==="string"&&/^\d+$/.test(f)?Number(f):f;return typeof w==="number"&&Number.isSafeInteger(w)&&w>=0?w:void 0}function Rn(f,w){return{message:f.message??w,...f.status!=null?{type:f.status}:{},...f.code!=null?{code:String(f.code)}:{}}}var Jo=async({response:f})=>{let w=f.headers.get("x-goog-upload-url");if(w==null)throw new P({data:f.headers,message:"Google did not return a resumable upload URL."});return{value:w}};function Yo(f){let w=f[0]?.modelId;if(w==null)throw new b({argument:"requests",message:"Google batches require at least one request."});for(let x of f)if(x.modelId!==w)throw new b({argument:"requests",message:"Google batches require every request to use the same model because the model is part of the batch endpoint."});return w}function Xo(f){let w=f.content.flatMap((A)=>A.type==="file"&&A.mediaType.startsWith("image/")&&A.data.type==="data"?[M(A.data.data)]:[]);if(w.length===0)return;let x=f.providerMetadata?.google??{};return{images:w,warnings:f.warnings,providerMetadata:{google:{...x,images:w.map(()=>({}))}},response:{timestamp:new Date,modelId:f.response?.modelId??"",headers:f.response?.headers},usage:{inputTokens:f.usage.inputTokens.total,outputTokens:f.usage.outputTokens.total,totalTokens:(f.usage.inputTokens.total??0)+(f.usage.outputTokens.total??0)}}}var Qo=S({id:"google.enterprise_web_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))});a(()=>s(U({fileSearchStoreNames:o(e()).describe("The names of the file_search_stores to retrieve from. Example: `fileSearchStores/my-file-search-store-123`"),topK:r().int().positive().describe("The number of file search retrieval chunks to retrieve.").optional(),metadataFilter:e().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()})));var Zo=S({id:"google.file_search",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),ei={googleSearch:Uo,enterpriseWebSearch:Qo,googleMaps:S({id:"google.google_maps",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),urlContext:S({id:"google.url_context",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))}),fileSearch:Zo,codeExecution:no,vertexRagStore:S({id:"google.vertex_rag_store",inputSchema:a(()=>s(t({}))),outputSchema:a(()=>s(t({})))})},ti=new Set(["gemini-2.5-flash-image","gemini-3-pro-image-preview","gemini-3.1-flash-image-preview","gemini-nano-banana-2.1"]),ni=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,{},w.config)}get maxImagesPerCall(){if(this.settings.maxImagesPerCall!=null)return this.settings.maxImagesPerCall;return 1}get supportsFileInputs(){return ti.has(this.modelId)?!0:void 0}get supportsMaskInputs(){return this.supportsFileInputs===!0?!1:void 0}get provider(){return this.config.provider}constructor(w,x,A){this.modelId=w,this.settings=x,this.config=A,this.specificationVersion="v4"}async doGenerate(w){if(!this.modelId.startsWith("gemini-"))throw Error("Google image models other than Gemini are no longer supported. Use a model ID that starts with `gemini-`.");let{prompt:x,size:A,aspectRatio:N,seed:B,providerOptions:re,headers:ee,abortSignal:V,files:pe,mask:ce}=w,Re=[];if(ce!=null)throw Error("Gemini image models do not support mask-based image editing.");if(A!=null)Re.push({type:"unsupported",feature:"size",details:"This model does not support the `size` option. Use `aspectRatio` instead."});let Le=[];if(x!=null)Le.push({type:"text",text:x});if(pe!=null&&pe.length>0)for(let De of pe)if(De.type==="url")Le.push({type:"file",data:{type:"url",url:new URL(De.url)},mediaType:"image/*"});else Le.push({type:"file",data:{type:"data",data:typeof De.data==="string"?De.data:new Uint8Array(De.data)},mediaType:De.mediaType});let Ce=[{role:"user",content:Le}],Ee=await h({provider:"google",providerOptions:re,schema:kn}),{googleSearch:je,responseModalities:Ne,imageConfig:ye,...ie}=re?.google??{},be=await new Ct(this.modelId,{provider:this.config.provider,baseURL:this.config.baseURL,headers:this.config.headers??{},fetch:this.config.fetch,generateId:this.config.generateId??C}).doGenerate({prompt:Ce,seed:B,providerOptions:{google:{...ie,responseModalities:["IMAGE"],imageConfig:N!=null||ye!=null?{...ye,...N!=null?{aspectRatio:N}:{}}:void 0}},tools:Ee?.googleSearch!=null?[{type:"provider",id:"google.google_search",name:"google_search",args:Ee.googleSearch}]:void 0,headers:ee,abortSignal:V}),ne=this.config._internal?.currentDate?.()??new Date,se=[];for(let De of be.content)if(De.type==="file"&&De.mediaType.startsWith("image/")&&De.data.type==="data")se.push(M(De.data.data));let Ue=be.providerMetadata?.google??{};return{images:se,...be.finishReason.unified==="content-filter"?{isRetryable:!1}:{},warnings:Re,providerMetadata:{google:{...Ue,finishReason:be.finishReason.raw??null,images:se.map(()=>({}))}},response:{timestamp:ne,modelId:this.modelId,headers:be.response?.headers},usage:be.usage?{inputTokens:be.usage.inputTokens.total,outputTokens:be.usage.outputTokens.total,totalTokens:(be.usage.inputTokens.total??0)+(be.usage.outputTokens.total??0)}:void 0}}},oi=class{get provider(){return this.config.provider}constructor(f){this.config=f,this.specificationVersion="v4"}async uploadFile(f){let w=await h({provider:"google",providerOptions:f.providerOptions,schema:ai}),x=d(this.config.headers(),f.headers),A=this.config.fetch??globalThis.fetch,N=[];if(f.filename!=null)N.push({type:"unsupported",feature:"filename"});let B=we(f.data),re=f.mediaType,ee=w?.displayName,V=await A(`${this.config.baseURL.replace(/\/v1beta$/,"")}/upload/v1beta/files`,{method:"POST",headers:{...x,"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(B.length),"X-Goog-Upload-Header-Content-Type":re,"Content-Type":"application/json"},body:JSON.stringify({file:{...ee!=null?{display_name:ee}:{}}}),signal:f.abortSignal});if(!V.ok){let je=await V.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to initiate resumable upload: ${V.status} ${je}`})}let pe=V.headers.get("x-goog-upload-url");if(!pe)throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:"No upload URL returned from initiation request"});let ce=await A(pe,{method:"POST",headers:{"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"},body:ii(B),signal:f.abortSignal});if(!ce.ok){let je=await ce.text();throw new m({name:"GOOGLE_FILES_UPLOAD_ERROR",message:`Failed to upload file data: ${ce.status} ${je}`})}let Re=(await ce.json()).file,Le=w?.pollIntervalMs??2000,Ce=w?.pollTimeoutMs??300000,Ee=Date.now();while(Re.state==="PROCESSING"){if(Date.now()-Ee>Ce)throw new m({name:"GOOGLE_FILES_UPLOAD_TIMEOUT",message:`File processing timed out after ${Ce}ms`});await Oe(Le,{abortSignal:f.abortSignal});let je=/^files\/([^/]+)$/.exec(Re.name),Ne=je!=null?`files/${de(je[1])}`:de(Re.name),{value:ye}=await R({url:`${this.config.baseURL}/${Ne}`,validateUrl:!1,headers:d(x),successfulResponseHandler:p(si),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});Re=ye}if(Re.state==="FAILED")throw new m({name:"GOOGLE_FILES_UPLOAD_FAILED",message:`File processing failed for ${Re.name}`});return{warnings:N,providerReference:{google:Re.uri},mediaType:Re.mimeType??f.mediaType,providerMetadata:{google:{name:Re.name,displayName:Re.displayName,mimeType:Re.mimeType,sizeBytes:Re.sizeBytes,state:Re.state,uri:Re.uri,...Re.createTime!=null?{createTime:Re.createTime}:{},...Re.updateTime!=null?{updateTime:Re.updateTime}:{},...Re.expirationTime!=null?{expirationTime:Re.expirationTime}:{},...Re.sha256Hash!=null?{sha256Hash:Re.sha256Hash}:{}}}}}};function ii(f){if(f.buffer instanceof ArrayBuffer)return f;return new Uint8Array(f)}var si=a(()=>s(t({name:e(),displayName:e().nullish(),mimeType:e(),sizeBytes:e().nullish(),createTime:e().nullish(),updateTime:e().nullish(),expirationTime:e().nullish(),sha256Hash:e().nullish(),uri:e(),state:e()}))),ai=a(()=>s(U({displayName:e().nullish(),pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish()}))),ri=a(()=>s(U({pollIntervalMs:r().positive().nullish(),pollTimeoutMs:r().positive().nullish(),personGeneration:i(["dont_allow","allow_adult","allow_all"]).nullish(),negativePrompt:e().nullish(),referenceImages:o(t({bytesBase64Encoded:e().nullish(),gcsUri:e().nullish()})).nullish()})));function li(f){return f.frameImages?.find((w)=>w.frameType==="first_frame")?.image}function ui(f){return li(f)??f.image}function ci(f){return f.frameImages?.find((w)=>w.frameType==="last_frame")?.image}function di(f){if(f.frameImages!=null&&f.frameImages.length>0)return;return f.inputReferences!=null&&f.inputReferences.length>0?f.inputReferences:void 0}function Dt(f,w){if(f.type==="url"){if(f.url.startsWith("gs://"))return{gcsUri:f.url,mimeType:"image/png"};w.push({type:"unsupported",feature:"URL-based image input",details:"Google Generative AI video models require base64-encoded images or GCS URIs. URL will be ignored."});return}return{bytesBase64Encoded:typeof f.data==="string"?f.data:X(f.data),mimeType:f.mediaType||"image/png"}}function pi(f){if(f.bytesBase64Encoded)return{image:{bytesBase64Encoded:f.bytesBase64Encoded,mimeType:"image/png"},referenceType:"asset"};if(f.gcsUri)return{image:{gcsUri:f.gcsUri,mimeType:"image/png"},referenceType:"asset"};return f}function gi(f,w){let x=Dt(f,w);return x!=null?{image:x,referenceType:"asset"}:void 0}var hi=class{get provider(){return this.config.provider}get maxVideosPerCall(){return 4}constructor(f,w){this.modelId=f,this.config=w,this.specificationVersion="v4"}async buildRequest(f){let w=[],x=await h({provider:"google",providerOptions:f.providerOptions,schema:ri}),A=[{}],N=A[0];if(f.prompt!=null)N.prompt=f.prompt;let B=ui(f);if(B!=null){let pe=Dt(B,w);if(pe!=null)N.image=pe}let re=ci(f);if(re!=null){let pe=Dt(re,w);if(pe!=null)N.lastFrame=pe}let ee=di(f);if(ee!=null)N.referenceImages=ee.flatMap((pe)=>{let ce=gi(pe,w);return ce!=null?[ce]:[]});else if(x?.referenceImages!=null)N.referenceImages=x.referenceImages.map((pe)=>pi(pe));let V={sampleCount:f.n};if(f.aspectRatio)V.aspectRatio=f.aspectRatio;if(f.resolution)V.resolution={"1280x720":"720p","1920x1080":"1080p","3840x2160":"4k"}[f.resolution]||f.resolution;if(f.duration)V.durationSeconds=f.duration;if(f.seed)V.seed=f.seed;if(x!=null){let pe=x;if(pe.personGeneration!==void 0&&pe.personGeneration!==null)V.personGeneration=pe.personGeneration;if(pe.negativePrompt!==void 0&&pe.negativePrompt!==null)V.negativePrompt=pe.negativePrompt;for(let[ce,Re]of Object.entries(pe))if(!["pollIntervalMs","pollTimeoutMs","personGeneration","negativePrompt","referenceImages"].includes(ce))V[ce]=Re}return{instances:A,parameters:V,warnings:w,googleOptions:x}}async buildCompletedResult(f,w,x,A){let N=f.response;if(!N?.generateVideoResponse?.generatedSamples||N.generateVideoResponse.generatedSamples.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:`No videos in response. Response: ${JSON.stringify(f)}`});let B=[],re=[],ee=(await _(this.config.headers))?.["x-goog-api-key"];for(let V of N.generateVideoResponse.generatedSamples)if(V.video?.uri){let pe=ee&&He(V.video.uri,this.config.baseURL)?`${V.video.uri}${V.video.uri.includes("?")?"&":"?"}key=${ee}`:V.video.uri;B.push({type:"url",url:pe,mediaType:"video/mp4"}),re.push({uri:V.video.uri})}if(B.length===0)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No valid videos in response"});return{status:"completed",videos:B,warnings:x,response:{timestamp:A,modelId:this.modelId,headers:w},providerMetadata:{google:{videos:re}}}}async doStart(f){let w=this.config._internal?.currentDate?.()??new Date,{instances:x,parameters:A,warnings:N}=await this.buildRequest(f),{value:B,responseHeaders:re}=await g({url:`${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,headers:d(await _(this.config.headers),f.headers),body:{instances:x,parameters:A},successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch}),ee=B.name;if(!ee)throw new m({name:"GOOGLE_VIDEO_GENERATION_ERROR",message:"No operation name returned from API"});return{operation:{operationName:ee},warnings:N,response:{timestamp:w,modelId:this.modelId,headers:re}}}async doStatus(f){let w=this.config._internal?.currentDate?.()??new Date,{operationName:x}=f.operation,{value:A,responseHeaders:N}=await R({url:`${this.config.baseURL}/${x}`,validateUrl:!1,headers:d(await _(this.config.headers),f.headers),successfulResponseHandler:p(ln),failedResponseHandler:Xe,abortSignal:f.abortSignal,fetch:this.config.fetch});if(!A.done)return{status:"pending",response:{timestamp:w,modelId:this.modelId,headers:N}};if(A.error)return{status:"error",error:`Video generation failed: ${A.error.message}`,response:{timestamp:w,modelId:this.modelId,headers:N}};return this.buildCompletedResult(A,N,[],w)}},ln=a(()=>s(t({name:e().nullish(),done:c().nullish(),error:t({code:r().nullish(),message:e(),status:e().nullish()}).nullish(),response:t({generateVideoResponse:t({generatedSamples:o(t({video:t({uri:e().nullish()}).nullish()})).nullish()}).nullish()}).nullish()}))),mi=a(()=>s(t({candidates:o(t({content:t({parts:o(t({inlineData:t({mimeType:e().nullish(),data:e().nullish()}).nullish()})).nullish()}).nullish()})).nullish(),usageMetadata:y(e(),G()).nullish()})));function fi({text:f,voice:w,providerOptions:x}){let A=x?.google,N=A!=null&&typeof A==="object"?A:void 0,B=N&&"turns"in N?N.turns:void 0,re=[];if(Array.isArray(B)&&B.length>0){for(let pe of B){if(pe==null||typeof pe!=="object"||!("text"in pe)||typeof pe.text!=="string")break;re.push(pe.text)}if(re.length===B.length)f=re.join("")}let ee=N&&"multiSpeakerVoiceConfig"in N?N.multiSpeakerVoiceConfig:void 0,V=ee!=null&&typeof ee==="object"&&"speakerVoiceConfigs"in ee&&Array.isArray(ee.speakerVoiceConfigs)?ee.speakerVoiceConfigs:[];return{text:f,usesCustomVoice:w?.startsWith("voice_")===!0||w?.startsWith("voicekey_")===!0||V.some((pe)=>pe!=null&&typeof pe==="object"&&("voiceConfig"in pe)&&pe.voiceConfig!=null&&typeof pe.voiceConfig==="object"&&("voice"in pe.voiceConfig))}}var yi=()=>t({voiceName:e()}),vi=()=>t({prebuiltVoiceConfig:yi(),voice:Ae().optional()}),un=()=>t({speaker:e().min(1).optional(),style:e().optional()}),cn=a(()=>s(t({speechMetadata:un().optional(),turns:o(t({text:e(),speechMetadata:un().optional()})).min(1).optional(),multiSpeakerVoiceConfig:t({speakerVoiceConfigs:o(t({speaker:e(),voiceConfig:vi()}))}).optional()}))),bi="Kore",Ti=24000,_i=class f{static[k](w){return E({modelId:w.modelId,config:w.config})}static[T](w){return new f(w.modelId,w.config)}get provider(){return this.config.provider}constructor(w,x){this.modelId=w,this.config=x,this.specificationVersion="v4"}async getArgs({text:w,voice:x=bi,outputFormat:A,instructions:N,speed:B,language:re,providerOptions:ee}){let V=[],pe=this.config.provider.includes("vertex")?["googleVertex","vertex"]:["google"],ce;for(let be of pe)if(ce=await h({provider:be,providerOptions:ee,schema:cn}),ce!=null)break;if(ce==null&&!pe.includes("google"))ce=await h({provider:"google",providerOptions:ee,schema:cn});let Re=!this.modelId.startsWith("gemini-2.5-")&&!this.modelId.startsWith("gemini-3.1-"),Le=fi({text:w,voice:x,providerOptions:{google:ce}});if(Le.usesCustomVoice)throw new b({argument:"voice",message:"Custom voices are not supported. Use a prebuilt voice instead."});let Ce=ce?.multiSpeakerVoiceConfig,Ee=Ce?{multiSpeakerVoiceConfig:Ce}:{voiceConfig:{prebuiltVoiceConfig:{voiceName:x}}},je=w;if(N!=null&&!Re)if(Ce)V.push({type:"unsupported",feature:"instructions",details:"Google Gemini TTS ignores `instructions` when `multiSpeakerVoiceConfig` is set, because prepending them would break multi-speaker transcript parsing."});else je=`${N}: ${w}`;let Ne=[{text:je}];if(Re){if(ce?.turns&&ce.speechMetadata)throw new b({argument:"providerOptions",message:"Set speechMetadata on each turn when using turns."});if(ce?.turns&&w!=="")V.push({type:"unsupported",feature:"text",details:"Google TTS turns replace the top-level text."});Ne=(ce?.turns??[{text:w,speechMetadata:ce?.speechMetadata}]).map((be)=>{let ne=be.speechMetadata?.style??N,se=be.speechMetadata?.speaker;if(Ce&&!Ce.speakerVoiceConfigs.some((Ue)=>Ue.speaker===se))throw new b({argument:"speechMetadata.speaker",message:"Every multi-speaker turn must specify a speechMetadata.speaker matching a configured speaker."});return{text:be.text,...ne!=null||se!=null?{speechMetadata:{style:ne,speaker:se}}:{}}})}else if(ce?.turns||ce?.speechMetadata)throw new b({argument:"providerOptions",message:"Structured speech metadata and turns require Gemini 3.8 TTS."});if(Le.text.length===0)throw new b({argument:"text",message:"Speech input must contain a non-empty transcript."});if(B!=null)V.push({type:"unsupported",feature:"speed",details:"Google Gemini TTS models do not support the `speed` option. It was ignored."});if(re!=null)V.push({type:"unsupported",feature:"language",details:"Google Gemini TTS models do not support the `language` option. Language is detected automatically from the input text."});let ye=Re?{wav:"AUDIO_WAV","audio/wav":"AUDIO_WAV",pcm:"AUDIO_L16","audio/l16":"AUDIO_L16",mulaw:"AUDIO_MULAW","audio/mulaw":"AUDIO_MULAW",alaw:"AUDIO_ALAW","audio/alaw":"AUDIO_ALAW"}:{wav:"AUDIO_WAV",pcm:"AUDIO_L16"},ie="wav";if(A!=null&&Object.prototype.hasOwnProperty.call(ye,A))ie=A;else if(A!=null)V.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${A}. Using wav instead.`});return{requestBody:{contents:[{role:"user",parts:Ne}],generationConfig:{responseModalities:["AUDIO"],speechConfig:Ee,...Re&&A!=null?{responseFormat:{audio:{mimeType:ye[ie]}}}:{}}},warnings:V,outputFormat:ye[ie],usesStructuredSpeech:Re}}async doGenerate(w){let x=this.config._internal?.currentDate?.()??new Date,{requestBody:A,warnings:N,outputFormat:B,usesStructuredSpeech:re}=await this.getArgs(w),{value:ee,responseHeaders:V,rawValue:pe}=await g({url:`${this.config.baseURL}/models/${this.modelId}:generateContent`,headers:d(this.config.headers?await _(this.config.headers):void 0,w.headers),body:A,failedResponseHandler:Xe,successfulResponseHandler:p(mi),abortSignal:w.abortSignal,fetch:this.config.fetch}),ce,Re;for(let Ne of ee.candidates??[]){for(let ye of Ne.content?.parts??[])if(ye.inlineData?.data){ce=ye.inlineData.data,Re=ye.inlineData.mimeType??void 0;break}if(ce!=null)break}let Le=Ci(Re)??Ti,Ce=ce!=null?j(ce):new Uint8Array(0),Ee=/^audio\/(?:l16|pcm)(?:;|$)/i.test(Re??"")||Re==null&&!re,je=B==="AUDIO_WAV"&&Ee&&Ce.length>0?wi(Ce,Le):Ce;if(B==="AUDIO_L16"&&Ce.length>0&&!re)N.push({type:"unsupported",feature:"outputFormat",details:`Returning raw PCM audio (signed 16-bit little-endian, mono, ${Le} Hz). These bytes have no container header and are not directly playable; see providerMetadata.google for the sample rate and mime type.`});return{audio:je,warnings:N,...ee.usageMetadata!=null&&{usage:ee.usageMetadata},request:{body:JSON.stringify(A)},response:{timestamp:x,modelId:this.modelId,headers:V,body:pe},providerMetadata:{google:{sampleRate:Le,mimeType:Re??null}}}}};function Ci(f){if(f==null)return;let w=/rate=(\d+)/.exec(f);return w?Number.parseInt(w[1],10):void 0}function wi(f,w){let B=w*2,re=f.length,ee=new ArrayBuffer(44+re),V=new DataView(ee);Ot(V,0,"RIFF"),V.setUint32(4,36+re,!0),Ot(V,8,"WAVE"),Ot(V,12,"fmt "),V.setUint32(16,16,!0),V.setUint16(20,1,!0),V.setUint16(22,1,!0),V.setUint32(24,w,!0),V.setUint32(28,B,!0),V.setUint16(32,2,!0),V.setUint16(34,16,!0),Ot(V,36,"data"),V.setUint32(40,re,!0);let pe=new Uint8Array(ee);return pe.set(f,44),pe}function Ot(f,w,x){for(let A=0;A<x.length;A++)f.setUint8(w+A,x.charCodeAt(A))}function Ht(f){if(f==null)return te();let w=f.total_input_tokens??0,x=f.total_output_tokens??0,A=f.total_thought_tokens??0,N=f.total_cached_tokens??0;return{inputTokens:{total:f.total_input_tokens??void 0,noCache:f.total_input_tokens==null?void 0:w-N,cacheRead:f.total_cached_tokens??void 0,cacheWrite:void 0},outputTokens:{total:f.total_output_tokens==null&&f.total_thought_tokens==null?void 0:x+A,text:f.total_output_tokens??void 0,reasoning:f.total_thought_tokens??void 0},raw:f}}function On(f){let w=f?.output_tokens_by_modality;if(w==null)return;let x={};for(let A of w)if(A?.modality!=null&&A.tokens!=null)x[A.modality]=A.tokens;return Object.keys(x).length>0?x:void 0}var Si={pdf:"application/pdf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};function Mn(f){let w=f.toLowerCase();for(let[x,A]of Object.entries(Si))if(w.endsWith(`.${x}`))return A;return"application/octet-stream"}function En(f){let w=f.split("/"),x=w[w.length-1];return x&&x.length>0?x:void 0}function Ii({annotation:f,generateId:w}){switch(f.type){case"url_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.title!=null?{title:x.title}:{}}}case"file_citation":{let x=f,A=x.url??x.document_uri??x.file_name;if(A==null||A.length===0)return;if(A.startsWith("http://")||A.startsWith("https://"))return{type:"source",sourceType:"url",id:w(),url:A,...x.file_name!=null?{title:x.file_name}:{}};let N=x.file_name??En(A),B=Mn(A);return{type:"source",sourceType:"document",id:w(),mediaType:B,title:x.file_name??N??A,...N!=null?{filename:N}:{}}}case"place_citation":{let x=f;if(x.url==null||x.url.length===0)return;return{type:"source",sourceType:"url",id:w(),url:x.url,...x.name!=null?{title:x.name}:{}}}default:return}}function An({block:f,generateId:w}){let x=[];switch(f.type){case"url_context_result":{let A=f.result??[];for(let N of A){if(N?.url==null||N.url.length===0)continue;if(N.status!=null&&N.status!=="success")continue;x.push({type:"source",sourceType:"url",id:w(),url:N.url})}break}case"google_search_result":{let A=f.result??[];for(let N of A){let B=N?.url;if(B==null||B.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B,...N.title!=null?{title:N.title}:{}})}break}case"google_maps_result":{let A=f.result??[];for(let N of A)for(let B of N.places??[]){if(B.url==null||B.url.length===0)continue;x.push({type:"source",sourceType:"url",id:w(),url:B.url,...B.name!=null?{title:B.name}:{}})}break}case"file_search_result":{let A=f.result??[];for(let N of A){if(N==null||typeof N!=="object")continue;let B=N,re=B.url??B.document_uri??B.file_name;if(re==null||re.length===0)continue;if(re.startsWith("http://")||re.startsWith("https://")){x.push({type:"source",sourceType:"url",id:w(),url:re,...B.title!=null?{title:B.title}:{}});continue}let ee=B.file_name??En(re),V=Mn(re);x.push({type:"source",sourceType:"document",id:w(),mediaType:V,title:B.title??B.file_name??ee??re,...ee!=null?{filename:ee}:{}})}break}}return x}function Pt({annotations:f,generateId:w}){if(f==null)return[];let x=new Set,A=[];for(let N of f){let B=Ii({annotation:N,generateId:w});if(B==null)continue;let re=B.sourceType==="url"?`url:${B.url}`:`doc:${B.filename??B.title}`;if(x.has(re))continue;x.add(re),A.push(B)}return A}function Vt({status:f,hasFunctionCall:w}){switch(f){case"completed":return w?"tool-calls":"stop";case"requires_action":return"tool-calls";case"failed":return"error";case"incomplete":return"length";case"cancelled":return"other";default:return"other"}}var ki=new Set(["google_search_call","code_execution_call","url_context_call","file_search_call","google_maps_call","mcp_server_tool_call"]),xi=new Set(["google_search_result","code_execution_result","url_context_result","file_search_result","google_maps_result","mcp_server_tool_result"]);function Ri(f){return f.replace(/_call$/,"")}function Oi(f){return f.replace(/_result$/,"")}function dn({warnings:f,generateId:w,includeRawChunks:x,serviceTier:A}){let N,B,re=A,ee,V=!1,pe=!1,ce=new Map,Re=new Set;function Le(Ce){return Ce.sourceType==="url"?`url:${Ce.url}`:`doc:${Ce.filename??Ce.title}`}return new TransformStream({start(Ce){Ce.enqueue({type:"stream-start",warnings:f})},transform(Ce,Ee){if(x)Ee.enqueue({type:"raw",rawValue:Ce.rawValue});if(!Ce.success){ee="failed",Ee.enqueue({type:"error",error:Ce.error});return}let je=Ce.value,Ne=je.event_type;switch(Ne){case"interaction.created":{let ye=je.interaction;N=ye?.id!=null&&ye.id.length>0?ye.id:void 0;let ie=ye?.created,be;if(typeof ie==="string"){let ne=new Date(ie);if(!Number.isNaN(ne.getTime()))be=ne}Ee.enqueue({type:"response-metadata",...N!=null?{id:N}:{},modelId:ye?.model,...be?{timestamp:be}:{}});break}case"step.start":{let ye=je,{step:ie,index:be}=ye,ne=`${N??"interaction"}:${be}`,se=ie?.type;if(se==="model_output"){let Ue=ie?.content?.[0];if(Ue?.type==="text"){ce.set(be,{kind:"text",id:ne,emittedSourceKeys:new Set}),Ee.enqueue({type:"text-start",id:ne});let De=Pt({annotations:Ue.annotations,generateId:w});for(let qe of De){let We=Le(qe);if(Re.has(We))continue;Re.add(We),Ee.enqueue(qe)}}else if(Ue?.type==="image")ce.set(be,{kind:"image",id:ne,...Ue.data!=null?{data:Ue.data}:{},...Ue.mime_type!=null?{mimeType:Ue.mime_type}:{},...Ue.uri!=null?{uri:Ue.uri}:{}});else ce.set(be,{kind:"pending_model_output",id:ne})}else if(se==="thought"){let Ue=ie?.signature;if(ce.set(be,{kind:"reasoning",id:ne,...Ue!=null?{signature:Ue}:{}}),Ee.enqueue({type:"reasoning-start",id:ne}),Array.isArray(ie?.summary)){for(let De of ie.summary)if(De?.type==="text"&&typeof De.text==="string")Ee.enqueue({type:"reasoning-delta",id:ne,delta:De.text})}}else if(se==="processing_call"||se==="processing_result"){let Ue={};if(ie?.signature!=null)Ue.signature=ie.signature;if(N!=null)Ue.interactionId=N;if(se==="processing_call")Ue.processingId=ie?.id||ne;else Ue.processingCallId=ie?.call_id||ne;ce.set(be,{kind:"custom",id:ne,customKind:`google.${se}`,google:Ue})}else if(se==="function_call"){let Ue=ie?.id||ne,De=ie?.name??"unknown";V=!0;let qe={kind:"function_call",id:ne,toolCallId:Ue,toolName:De,argumentsAccum:"",...ie?.signature!=null?{signature:ie.signature}:{}};ce.set(be,qe),Ee.enqueue({type:"tool-input-start",id:Ue,toolName:De})}else if(se!=null&&ki.has(se)){let Ue=se==="mcp_server_tool_call"?ie?.name??"mcp_server_tool":Ri(se),De={kind:"builtin_tool_call",id:ne,blockType:se,toolCallId:ie?.id||ne,toolName:Ue,arguments:ie?.arguments??{},callEmitted:!1};ce.set(be,De)}else if(se!=null&&xi.has(se)){let Ue=se==="mcp_server_tool_result"?ie?.name??"mcp_server_tool":Oi(se),De={kind:"builtin_tool_result",id:ne,blockType:se,callId:ie?.call_id||ne,toolName:Ue,result:ie?.result??null,...ie?.is_error!=null?{isError:ie.is_error}:{},resultEmitted:!1};ce.set(be,De)}else ce.set(be,{kind:"unknown",id:ne});break}case"step.delta":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;let be=ye.delta?.type;if(ie.kind==="pending_model_output"){if(be==="text"||be==="text_annotation"||be==="text_annotation_delta"){let se={kind:"text",id:ie.id,emittedSourceKeys:new Set};ce.set(ye.index,se),ie=se,Ee.enqueue({type:"text-start",id:se.id})}}if(be==="image"&&(ie.kind==="pending_model_output"||ie.kind==="text"||ie.kind==="image")){let se=ye.delta,Ue={};if(N!=null)Ue.interactionId=N;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"image/png",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});if(ie.kind==="image")ie.data=void 0,ie.uri=void 0;break}if(be==="video"&&(ie.kind==="pending_model_output"||ie.kind==="text")){let se=ye.delta,Ue={};if(N!=null)Ue.interactionId=N;let De=Object.keys(Ue).length>0?{google:Ue}:void 0;if(se?.data!=null&&se.data.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"data",data:se.data},...De?{providerMetadata:De}:{}});else if(se?.uri!=null&&se.uri.length>0)Ee.enqueue({type:"file",mediaType:se.mime_type??"video/mp4",data:{type:"url",url:new URL(se.uri)},...De?{providerMetadata:De}:{}});break}let ne=ye.delta;if(ie.kind==="custom"&&(ne?.type==="processing_call"||ne?.type==="processing_result")){if(ne.signature!=null)ie.google.signature=ne.signature;if(ne.type==="processing_call"&&ne.id!=null&&ne.id.length>0)ie.google.processingId=ne.id;if(ne.type==="processing_result"&&ne.call_id!=null&&ne.call_id.length>0)ie.google.processingCallId=ne.call_id}else if(ie.kind==="text"&&ne?.type==="text"){let se=ne.text??"";if(se.length>0)Ee.enqueue({type:"text-delta",id:ie.id,delta:se})}else if(ie.kind==="text"&&(ne?.type==="text_annotation"||ne?.type==="text_annotation_delta")){let se=Pt({annotations:ne.annotations,generateId:w});for(let Ue of se){let De=Le(Ue);if(Re.has(De))continue;Re.add(De),ie.emittedSourceKeys.add(De),Ee.enqueue(Ue)}}else if(ie.kind==="image"&&ne?.type==="image"){if(ne.data!=null)ie.data=ne.data;if(ne.mime_type!=null)ie.mimeType=ne.mime_type;if(ne.uri!=null)ie.uri=ne.uri}else if(ie.kind==="reasoning"){if(ne?.type==="thought_summary"){let se=ne.content;if(se?.type==="text"&&typeof se.text==="string")Ee.enqueue({type:"reasoning-delta",id:ie.id,delta:se.text})}else if(ne?.type==="thought_signature"){let se=ne.signature;if(se!=null)ie.signature=se}}else if(ie.kind==="function_call"&&ne?.type==="arguments_delta"){let se=typeof ne.arguments==="string"?ne.arguments:"";if(se.length>0)ie.argumentsAccum+=se,Ee.enqueue({type:"tool-input-delta",id:ie.toolCallId,delta:se});if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.signature!=null)ie.signature=ne.signature;V=!0}else if(ie.kind==="builtin_tool_call"&&ne?.type===ie.blockType){if(ne.id!=null&&ne.id.length>0)ie.toolCallId=ne.id;if(ne.arguments!=null&&typeof ne.arguments==="object")ie.arguments=ne.arguments;if(ne.name!=null&&ie.blockType==="mcp_server_tool_call")ie.toolName=ne.name}else if(ie.kind==="builtin_tool_result"&&ne?.type===ie.blockType){if(ne.call_id!=null&&ne.call_id.length>0)ie.callId=ne.call_id;if(ne.result!==void 0)ie.result=ne.result;if(ne.is_error!=null)ie.isError=ne.is_error;if(ne.name!=null&&ie.blockType==="mcp_server_tool_result")ie.toolName=ne.name}break}case"step.stop":{let ye=je,ie=ce.get(ye.index);if(ie==null)break;if(ie.kind==="text"){let be=N!=null?{google:{interactionId:N}}:void 0;Ee.enqueue({type:"text-end",id:ie.id,...be?{providerMetadata:be}:{}})}else if(ie.kind==="reasoning"){let be={};if(ie.signature!=null)be.signature=ie.signature;if(N!=null)be.interactionId=N;let ne=Object.keys(be).length>0?{google:be}:void 0;Ee.enqueue({type:"reasoning-end",id:ie.id,...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="image"){let be={};if(N!=null)be.interactionId=N;let ne=Object.keys(be).length>0?{google:be}:void 0;if(ie.data!=null&&ie.data.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"data",data:ie.data},...ne?{providerMetadata:ne}:{}});else if(ie.uri!=null&&ie.uri.length>0)Ee.enqueue({type:"file",mediaType:ie.mimeType??"image/png",data:{type:"url",url:new URL(ie.uri)},...ne?{providerMetadata:ne}:{}})}else if(ie.kind==="function_call"){let be=ie.argumentsAccum.length>0?ie.argumentsAccum:"{}";Ee.enqueue({type:"tool-input-end",id:ie.toolCallId});let ne={};if(ie.signature!=null)ne.signature=ie.signature;if(N!=null)ne.interactionId=N;let se=Object.keys(ne).length>0?{google:ne}:void 0;Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:be,...se?{providerMetadata:se}:{}})}else if(ie.kind==="custom")Ee.enqueue({type:"custom",kind:ie.customKind,providerMetadata:{google:ie.google}});else if(ie.kind==="builtin_tool_call"&&!ie.callEmitted)Ee.enqueue({type:"tool-call",toolCallId:ie.toolCallId,toolName:ie.toolName,input:JSON.stringify(ie.arguments??{}),providerExecuted:!0}),ie.callEmitted=!0;else if(ie.kind==="builtin_tool_result"&&!ie.resultEmitted){Ee.enqueue({type:"tool-result",toolCallId:ie.callId,toolName:ie.toolName,result:ie.result??null}),ie.resultEmitted=!0;let be=An({block:{type:ie.blockType,call_id:ie.callId,result:ie.result},generateId:w});for(let ne of be){let se=Le(ne);if(Re.has(se))continue;Re.add(se),Ee.enqueue(ne)}}ce.delete(ye.index);break}case"interaction.status_update":case"interaction.in_progress":case"interaction.requires_action":{let ye=je;if(ye.status!=null)ee=ye.status;else if(Ne==="interaction.requires_action")ee="requires_action";else ee="in_progress";break}case"interaction.completed":{pe=!0;let ye=je.interaction;if(ye?.id!=null&&ye.id.length>0)N=ye.id;if(ye?.status!=null)ee=ye.status;if(ye?.usage!=null)B=ye.usage;if(ye?.service_tier!=null)re=ye.service_tier;break}case"error":{let ye=je;ee="failed",Ee.enqueue({type:"error",error:xe({message:ye.error?.message??"Unknown interaction error",type:ye.event_type,code:ye.error?.code??void 0,data:ye})});break}}},flush(Ce){let Ee=!pe&&(ee==null||ee==="in_progress"),je={unified:Ee?"interrupted":Vt({status:ee,hasFunctionCall:V}),raw:Ee?void 0:ee},Ne=On(B),ye={google:{...N!=null?{interactionId:N}:{},...re!=null?{serviceTier:re}:{},...Ne!=null?{outputTokensByModality:Ne}:{}}};Ce.enqueue({type:"finish",finishReason:je,usage:Ht(B),providerMetadata:ye})}})}function Mi({prompt:f,previousInteractionId:w,store:x,mediaResolution:A}){let N=[],B=w!=null&&x===!1,re=w!=null&&x!==!1;if(B)N.push({type:"other",message:"google.interactions: providerOptions.google.previousInteractionId was set together with store: false. These are incoherent (the prior interaction cannot be referenced when nothing was stored on the server); the full history will be sent and previous_interaction_id will still be emitted."});let ee=re?Ai({prompt:f,previousInteractionId:w}):f,V=[],pe=[];for(let ce of ee)switch(ce.role){case"system":V.push(ce.content);break;case"user":{let Re=[];for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:N,mediaResolution:A});if(Ee!=null)Re.push(Ee)}let Le=Ni(Re);if(Le.length>0)pe.push({type:"user_input",content:Le});break}case"assistant":{let Re=[],Le=()=>{if(Re.length>0)pe.push({type:"model_output",content:Re}),Re=[]};for(let Ce of ce.content)if(Ce.type==="text")Re.push({type:"text",text:Ce.text});else if(Ce.type==="reasoning"){Le();let Ee=Ce.providerOptions?.google?.signature;pe.push({type:"thought",...Ee!=null?{signature:Ee}:{},summary:Ce.text.length>0?[{type:"text",text:Ce.text}]:void 0})}else if(Ce.type==="file"){let Ee=pn({part:Ce,warnings:N,mediaResolution:A});if(Ee!=null)Re.push(Ee)}else if(Ce.type==="custom"){Le();let Ee=Ce.providerOptions?.google,je=typeof Ee?.signature==="string"?Ee.signature:void 0;if(Ce.kind==="google.processing_call"&&typeof Ee?.processingId==="string")pe.push({type:"processing_call",id:Ee.processingId,...je!=null?{signature:je}:{}});else if(Ce.kind==="google.processing_result"&&typeof Ee?.processingCallId==="string")pe.push({type:"processing_result",call_id:Ee.processingCallId,...je!=null?{signature:je}:{}});else N.push({type:"other",message:`google.interactions: unsupported or invalid custom assistant content part "${Ce.kind}"; part dropped.`})}else if(Ce.type==="tool-call"){Le();let Ee=Ce.providerOptions?.google?.signature,je=typeof Ce.input==="string"?Li(Ce.input):Ce.input??{};pe.push({type:"function_call",id:Ce.toolCallId,name:Ce.toolName,arguments:je,...Ee!=null?{signature:Ee}:{}})}else N.push({type:"other",message:`google.interactions: unsupported assistant content part type "${Ce.type}"; part dropped.`});Le();break}case"tool":{let Re=[];for(let Le of ce.content){if(Le.type!=="tool-result"){N.push({type:"other",message:`google.interactions: unsupported tool message part type "${Le.type}"; part dropped.`});continue}let Ce=ji({toolCallId:Le.toolCallId,toolName:Le.toolName,output:Le.output,signature:Le.providerOptions?.google?.signature,warnings:N});Re.push(Ce)}if(Re.length>0)pe.push({type:"user_input",content:Re});break}}return{input:pe,systemInstruction:V.length>0?V.join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Re,ht,De,Qe,Le,Ue,yt,bt}from"./embed-
|
|
1
|
+
import{Re,ht,De,Qe,Le,Ue,yt,bt}from"./embed-hm6mmwpk.js";var i="https://maxgfr.github.io/murmur/cdn/models.json";function l(e){let r=e.endpoint?Ue(e.endpoint):null;if(!r)return null;let o=e.model||"default",t={apiKey:"",model:o,customEndpoint:r,customModel:o};if(e.headers)t.headers=e.headers;return t}function d(e,r={}){let o=r.storageKey??"murmur",t={};if(e.provider)t.providerId=e.provider;if(e.model)t.model=e.model;return bt({catalog:ht({fallbackUrl:r.catalogUrl??i}),storage:yt({prefsKey:`${o}-llm`,dbName:`${o}-secrets`}),recommended:e.provider?[e.provider,...Re.filter((n)=>n!==e.provider)]:Re,defaults:t})}async function m(e,r){let o=l(e);if(o)return o;let t=r?await r.load():null;return t&&Le(t)?t:null}export{De as describeError,Le as isConfigured,Qe as loadModel,l as proxySettings,m as resolveSettings,d as visitorStore};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Tt,ft,Mt}from"./embed-
|
|
1
|
+
import{Tt,ft,Mt}from"./embed-3x3yz3jw.js";var E="script,style,noscript,template,svg,canvas,iframe,nav,header,footer,aside,form,button,dialog,[hidden],[aria-hidden='true'],[data-murmur-ignore],murmur-chat",O="main,article,[role='main'],body",D=/^(P|LI|DT|DD|PRE|BLOCKQUOTE|TABLE|TR|FIGCAPTION|DIV|SECTION|ARTICLE|UL|OL|DL|MAIN|H[1-6])$/;function g(o,{root:l=O,exclude:s=E}={}){let r=l.split(",").map((t)=>o.querySelector(t.trim())).find((t)=>!!t),p=r?.querySelector("h1")?.textContent?.replace(/\s+/g," ").trim()||o.querySelector("title")?.textContent?.trim()||"";if(!r)return{title:p,sections:[]};let u=[],e={heading:"",anchor:"",text:""},d=new Map,f=(t)=>{if(t.nodeType===3){e.text+=(t.textContent??"").replace(/\s+/g," ");return}if(t.nodeType!==1)return;let n=t;if(n.matches(s))return;let i=n.tagName.toUpperCase();if(/^H[1-3]$/.test(i)){u.push(e);let c=(n.textContent??"").replace(/\s+/g," ").trim(),m=n.id||n.closest("[id]")?.id||"";if(!m){let a=ft(c),x=d.get(a)??0;d.set(a,x+1),m=x?`${a}-${x}`:a}e={heading:c,anchor:m,text:""};return}if(i==="BR")e.text+=`
|
|
2
2
|
`;if((i==="TD"||i==="TH")&&!/(^|\n)\s*$/.test(e.text))e.text+=" | ";let h=D.test(i);if(h)e.text+=`
|
|
3
3
|
|
|
4
4
|
`;if(i==="LI")e.text+="- ";for(let c of Array.from(n.childNodes))f(c);if(h)e.text+=`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Re,ht,De,Qe,Le,Ue,
|
|
1
|
+
import{Re,ht,De,Qe,Le,Ue,yn,yt,bt}from"./embed-hm6mmwpk.js";export{Re as DEFAULT_RECOMMENDED,yn as ENDPOINT_PRESETS,bt as createLlmSettingsStore,De as describeError,Le as isConfigured,ht as liveCatalog,Qe as loadModel,yt as secureStorage,Ue as validateEndpoint};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Tn,St}from"./embed-gx1epk52.js";export{Tn as generateText,St as streamText};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N}from"./embed-
|
|
1
|
+
import{N}from"./embed-b072jtkd.js";var l={id:"onnx-community/LFM3-1.7B-ONNX",dtype:"q4f16",name:"LFM3 1.7B",sizeMB:1090};async function L(){let e=globalThis.navigator?.gpu;if(!e)return!1;try{return!!await e.requestAdapter()}catch{return!1}}function M(e){return e.flatMap((t)=>{if(t.role==="system")return[{role:"system",content:t.content}];if(t.role==="tool")return[];let o=t.content.map((n)=>n.type==="text"?n.text:"").join("").trim();return o?[{role:t.role,content:o}]:[]})}var d=new Map,x=new Set,y=new Map,_=(e)=>`${e.id}@${e.dtype}`,h="transformers-cache";async function S(e=l){try{if(typeof caches>"u"||!await caches.has(h))return!1;let t=await caches.open(h),o=`/${e.id}/resolve/`,n=`model_${e.dtype}.onnx`;return(await t.keys()).some((a)=>a.url.includes(o)&&a.url.includes(n))}catch{return!1}}async function P(){try{let e=globalThis.navigator?.storage;if(!e?.persist)return!1;return await e.persisted?.()||await e.persist()}catch{return!1}}function v(e=l,t){let o=_(e),n=y.get(o)??new Set;if(y.set(o,n),t)n.add(t);let a=d.get(o);if(!a)a=(async()=>{if(!await L())throw new p("webgpu","This browser has no WebGPU.");if(!await S(e))P();let{pipeline:r}=await (N("3m8jygmc"),import("./transformers.web-3m8jygmc.js")),i=await r("text-generation",e.id,{dtype:e.dtype,device:"webgpu",progress_callback:(s)=>{if(s.status!=="progress_total")return;let u={loaded:s.loaded??0,total:s.total??0,progress:Math.min(1,(s.progress??0)/100)};for(let c of n)c(u)}}).catch((s)=>{throw new p("load",s instanceof Error?s.message:String(s))});return x.add(o),i})(),a.catch(()=>d.delete(o)),d.set(o,a);return a}class p extends Error{code;constructor(e,t){super(t);this.code=e;this.name="LocalModelError"}}var k=(e,t)=>({inputTokens:{total:e,noCache:e,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:t,text:t,reasoning:void 0}});function q(e={}){let t=e.spec??l;async function o(n,a){let r=await v(t,e.onProgress),{TextStreamer:i,InterruptableStoppingCriteria:s,StoppingCriteriaList:u}=await (N("3m8jygmc"),import("./transformers.web-3m8jygmc.js")),c=new s,g=new u;g.push(c);let m=()=>c.interrupt();n.abortSignal?.addEventListener("abort",m,{once:!0});let f=0,b=new i(r.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,decode_kwargs:{clean_up_tokenization_spaces:!1},callback_function:(w)=>{if(w)a(w)},token_callback_function:()=>{f++}});try{await r(M(n.prompt),{max_new_tokens:n.maxOutputTokens??e.maxNewTokens??512,do_sample:!0,temperature:n.temperature??0.1,top_k:50,repetition_penalty:1.1,streamer:b,stopping_criteria:g,tokenizer_encode_kwargs:{enable_thinking:!1}})}finally{n.abortSignal?.removeEventListener("abort",m)}return{tokens:f,interrupted:c.interrupted}}return{specificationVersion:"v4",provider:"murmur-local",modelId:t.id,supportedUrls:{},async doGenerate(n){let a="",{tokens:r,interrupted:i}=await o(n,(s)=>{a+=s});return{content:[{type:"text",text:a}],finishReason:{unified:i?"other":"stop",raw:void 0},usage:k(0,r),warnings:[]}},async doStream(n){return{stream:new ReadableStream({start(r){r.enqueue({type:"stream-start",warnings:[]}),r.enqueue({type:"text-start",id:"0"}),o(n,(i)=>r.enqueue({type:"text-delta",id:"0",delta:i})).then(({tokens:i,interrupted:s})=>{r.enqueue({type:"text-end",id:"0"}),r.enqueue({type:"finish",finishReason:{unified:s?"other":"stop",raw:void 0},usage:k(0,i)}),r.close()},(i)=>{r.enqueue({type:"error",error:i}),r.close()})}})}}}}export{l as DEFAULT_LOCAL_MODEL,L as hasWebGPU,S as isLocalModelCached,v as loadLocalModel,q as localModel};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{oe,Ie}from"./embed-wyxkzaf2.js";import{b,Ge,me,u,e,r,c,ie,o,t,l,f,y,i,n,G,k,T,d,j,M,ee,te,le,F,z,C,jt,he,W,Se,ct,a,s,h,g,ne,ve,S,O,I,D,p,E,Ce,Y}from"./embed-3swpcbya.js";var xe=t({messages:o(G()).nullish(),cached_tokens:r().nullish(),audio_tokens:r().nullish()}).catchall(G()),Ue=t({reasoning_tokens:r().nullish()}).catchall(G()),_e=t({prompt_tokens:r(),completion_tokens:r(),total_tokens:r(),prompt_audio_seconds:r().nullish(),request_count:r().nullish(),service_tier:e().nullish(),num_cached_tokens:r().nullish(),prompt_tokens_details:xe.nullish(),prompt_token_details:xe.nullish(),completion_tokens_details:Ue.nullish()}).catchall(G());function pe(w){if(w==null)return te();let{prompt_tokens:m,completion_tokens:_}=w,H=w.num_cached_tokens??w.prompt_tokens_details?.cached_tokens??w.prompt_token_details?.cached_tokens??0;return{inputTokens:{total:m,noCache:m-H,cacheRead:H||void 0,cacheWrite:void 0},outputTokens:{total:_,text:_,reasoning:void 0},raw:w}}function ke({part:w}){if(w.data.type==="url")return w.data.url.toString();if(w.data.type==="data")return`data:${O({part:w})};base64,${M(w.data.data)}`;throw new u({functionality:`file part data type ${w.data.type}`})}function be(w){let m=[];for(let _=0;_<w.length;_++){let{role:H,content:L}=w[_],v=_===w.length-1;switch(H){case"system":m.push({role:"system",content:L});break;case"user":m.push({role:"user",content:L.map((q)=>{switch(q.type){case"text":return{type:"text",text:q.text};case"file":switch(q.data.type){case"reference":throw new u({functionality:"file parts with provider references"});case"text":throw new u({functionality:"text file parts"});case"url":case"data":if(z(q.mediaType)==="image")return{type:"image_url",image_url:ke({part:q})};else{if(q.data.type==="data"){if(O({part:q})!=="application/pdf")throw new u({functionality:"Only images and PDF file parts are supported"})}else if(q.mediaType!=="application/pdf")throw new u({functionality:"Only images and PDF file parts are supported"});return{type:"document_url",document_url:ke({part:q})}}}}})});break;case"assistant":{let q="",N=!1,x=[],R=[];for(let A of L)switch(A.type){case"text":q+=A.text,x.push({type:"text",text:A.text});break;case"tool-call":R.push({id:A.toolCallId,type:"function",function:{name:A.toolName,arguments:JSON.stringify(A.input)}});break;case"reasoning":N=!0,x.push({type:"thinking",thinking:[{type:"text",text:A.text}],closed:!0});break;default:throw Error(`Unsupported content type in assistant message: ${A.type}`)}m.push({role:"assistant",content:N?x:q,prefix:v?!0:void 0,tool_calls:R.length>0?R:void 0});break}case"tool":for(let q of L){if(q.type==="tool-approval-response")continue;let N=q.output,x;switch(N.type){case"text":case"error-text":x=N.value;break;case"execution-denied":x=N.reason??"Tool call execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(N.value)}m.push({role:"tool",name:q.toolName,tool_call_id:q.toolCallId,content:x})}break;default:throw Error(`Unsupported role: ${H}`)}}return m}function je(w){switch(w){case"stop":return"stop";case"length":case"model_length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"other"}}var Ee=()=>t({safePrompt:c().optional(),documentImageLimit:r().optional(),documentPageLimit:r().optional(),structuredOutputs:c().optional(),strictJsonSchema:c().optional(),parallelToolCalls:c().optional(),promptCacheKey:e().optional(),reasoningEffort:i(["high","none","low","max"]).optional()}),$e=a(()=>s(Ee())),De=a(()=>s(t({object:n("error"),message:e(),type:e(),param:e().nullable(),code:e().nullable()}))),ce=I({errorSchema:De,errorToMessage:(w)=>w.message});function Pe({tools:w,toolChoice:m}){w=w?.length?w:void 0;let _=[];if(w==null)return{tools:void 0,toolChoice:void 0,toolWarnings:_};let H=[];for(let v of w)if(v.type==="provider")_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`});else H.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:H,toolChoice:void 0,toolWarnings:_};let L=m.type;switch(L){case"auto":case"none":return{tools:H,toolChoice:L,toolWarnings:_};case"required":return{tools:H,toolChoice:"any",toolWarnings:_};case"tool":return{tools:H.filter((v)=>v.function.name===m.toolName),toolChoice:"any",toolWarnings:_};default:throw new u({functionality:`tool choice type: ${L}`})}}var Ve=new Set(["codestral-2508","codestral-latest","ministral-14b-2512","ministral-14b-latest","ministral-3b-2512","ministral-3b-latest","ministral-8b-2512","ministral-8b-latest","mistral-code-fim-latest","mistral-code-latest","mistral-large-latest","mistral-large-2512","voxtral-small-2507","voxtral-small-latest"]),Je=new Set(["zai-glm-5","zai-glm-5-3","zai-glm-5-3-flash","zai-glm-latest"]),ze=class w{static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.supportedUrls={"application/pdf":[/^https:\/\/.*$/]},this.modelId=m,this.config=_,this.generateId=_.generateId??C}get provider(){return this.config.provider}async getArgs({prompt:m,maxOutputTokens:_,temperature:H,topP:L,topK:v,frequencyPenalty:q,presencePenalty:N,reasoning:x,stopSequences:R,responseFormat:A,seed:U,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],V=await h({provider:"mistral",providerOptions:X,schema:$e})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=!Ve.has(this.modelId),K;if(re){let de=Je.has(this.modelId);if(V.reasoningEffort==null&&x==="none"&&de)Z.push({type:"compatibility",feature:"reasoning",details:'reasoning "none" is not directly supported by this model. mapped to effort "low".'});K=V.reasoningEffort??(W(x)?x==="none"?de?"low":"none":Se({reasoning:x,effortMap:de?{minimal:"low",low:"low",medium:"high",high:"high",xhigh:"max",max:"max"}:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},warnings:Z}):void 0)}else if(W(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let J=V.structuredOutputs??!0,P=V.strictJsonSchema??!1;if(A?.type==="json"&&(!J||A.schema==null))m=jt({messages:m,schema:A.schema});let B={model:this.modelId,safe_prompt:V.safePrompt,max_tokens:_,temperature:H,top_p:L,...q!=null?{frequency_penalty:q}:{},...N!=null?{presence_penalty:N}:{},stop:R,random_seed:U,reasoning_effort:K,response_format:A?.type==="json"?J&&A?.schema!=null?{type:"json_schema",json_schema:{schema:A.schema,strict:P,name:A.name??"response",description:A.description}}:{type:"json_object"}:void 0,document_image_limit:V.documentImageLimit,document_page_limit:V.documentPageLimit,...V.promptCacheKey!==void 0?{prompt_cache_key:V.promptCacheKey}:{},messages:be(m)},{tools:ae,toolChoice:fe,toolWarnings:ye}=Pe({tools:se,toolChoice:Q});return{args:{...B,tools:ae,tool_choice:fe,...ae!=null&&V.parallelToolCalls!==void 0?{parallel_tool_calls:V.parallelToolCalls}:{}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:H}=await this.getArgs(m),{responseHeaders:L,value:v,rawValue:q}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:_,failedResponseHandler:ce,successfulResponseHandler:p(Ke),abortSignal:m.abortSignal,fetch:this.config.fetch}),N=v.choices[0],x=[];if(N.message.content!=null&&Array.isArray(N.message.content)){for(let R of N.message.content)if(R.type==="thinking"){let A=Te(R.thinking);if(A.length>0)x.push({type:"reasoning",text:A})}else if(R.type==="text"){if(R.text.length>0)x.push({type:"text",text:R.text})}}else{let R=Me(N.message.content);if(R!=null&&R.length>0)x.push({type:"text",text:R})}if(N.message.tool_calls!=null)for(let R of N.message.tool_calls)x.push({type:"tool-call",toolCallId:R.id,toolName:R.function.name,input:R.function.arguments});return{content:x,finishReason:{unified:je(N.finish_reason),raw:N.finish_reason??void 0},usage:pe(v.usage),request:{body:_},response:{...ee(v),headers:L,body:q},warnings:H}}async doStream(m){let{args:_,warnings:H}=await this.getArgs(m),L={..._,stream:!0},{responseHeaders:v,value:q}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:L,failedResponseHandler:ce,successfulResponseHandler:D(Be),abortSignal:m.abortSignal,fetch:this.config.fetch}),N={unified:"interrupted",raw:void 0},x=void 0,R=!0,A=!1,U=null,X,se=this.generateId;return{stream:q.pipeThrough(new TransformStream({start(Q){X=new Ce(Q,{generateId:se}),Q.enqueue({type:"stream-start",warnings:H})},transform(Q,Z){if(m.includeRawChunks)Z.enqueue({type:"raw",rawValue:Q.rawValue});if(!Q.success){N={unified:"error",raw:void 0},Z.enqueue({type:"error",error:Q.error});return}let V=Q.value;if(R)R=!1,Z.enqueue({type:"response-metadata",...ee(V)});if(V.usage!=null)x=V.usage;let re=V.choices[0],K=re.delta,J=Me(K.content);if(K.content!=null&&Array.isArray(K.content)){for(let P of K.content)if(P.type==="thinking"){let B=Te(P.thinking);if(B.length>0){if(U==null){if(A)Z.enqueue({type:"text-end",id:"0"}),A=!1;U=se(),Z.enqueue({type:"reasoning-start",id:U})}Z.enqueue({type:"reasoning-delta",id:U,delta:B})}}}if(J!=null&&J.length>0){if(!A){if(U!=null)Z.enqueue({type:"reasoning-end",id:U}),U=null;Z.enqueue({type:"text-start",id:"0"}),A=!0}Z.enqueue({type:"text-delta",id:"0",delta:J})}if(K?.tool_calls!=null)for(let P of K.tool_calls)X.processDelta(P);if(re.finish_reason!=null)N={unified:je(re.finish_reason),raw:re.finish_reason}},flush(Q){if(U!=null)Q.enqueue({type:"reasoning-end",id:U});if(A)Q.enqueue({type:"text-end",id:"0"});X.flush(),Q.enqueue({type:"finish",finishReason:N,usage:pe(x)})}})),request:{body:L},response:{headers:v}}}};function Te(w){return w.filter((m)=>m.type==="text").map((m)=>m.text).join("")}function Me(w){if(typeof w==="string")return w;if(w==null)return;let m=[];for(let _ of w){let{type:H}=_;switch(H){case"text":m.push(_.text);break;case"thinking":case"image_url":case"reference":break;default:throw Error(`Unsupported type: ${H}`)}}return m.length?m.join(""):void 0}var qe=()=>l([e(),o(f("type",[t({type:n("text"),text:e()}),t({type:n("image_url"),image_url:l([e(),t({url:e(),detail:e().nullable()})])}),t({type:n("reference"),reference_ids:o(l([e(),r()]))}),t({type:n("thinking"),thinking:o(t({type:n("text"),text:e()}))})]))]).nullish(),Ke=a(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({message:t({role:n("assistant"),content:qe(),tool_calls:o(t({id:e(),function:t({name:e(),arguments:e()})})).nullish()}),index:r(),finish_reason:e().nullish()})),object:n("chat.completion"),usage:_e}))),Be=a(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({delta:t({role:i(["assistant"]).optional(),content:qe(),tool_calls:o(t({index:r().nullish(),id:e().nullish(),function:t({name:e().nullish(),arguments:e().nullish()})})).nullish()}),finish_reason:e().nullish(),index:r()})),usage:_e.nullish()})));function We(w,m){let _=[],H=[],L=new Set,v=(q)=>{if(L.has(q.toolCallId)){let x=null;if(q.output.type==="json"){let R=q.output.value,A=R!=null&&typeof R==="object"&&"info"in R?R.info:void 0;if(A!=null&&typeof A==="object"&&!Array.isArray(A))x="result"in A?A.result??A:A}_.push({type:"function.result",tool_call_id:q.toolCallId,result:typeof x==="string"?x:JSON.stringify(x)});return}let N=be([{role:"tool",content:[q]}])[0];_.push({type:"function.result",tool_call_id:q.toolCallId,result:N.content})};for(let q of w)switch(q.role){case"system":H.push(q.content);break;case"user":{let N=be([q])[0];if(N.role==="user")_.push({type:"message.input",role:"user",content:N.content});break}case"assistant":{let N=[],x=()=>{if(N.length>0)_.push({type:"message.input",role:"assistant",content:N}),N=[]};for(let R of q.content)switch(R.type){case"text":N.push({type:"text",text:R.text});break;case"reasoning":N.push({type:"thinking",thinking:[{type:"text",text:R.text}],closed:!0});break;case"tool-call":if(x(),R.providerExecuted){let A=R.providerOptions?.mistral?.function??R.providerOptions?.mistral?.name,U=R.input;_.push({type:"function.call",tool_call_id:R.toolCallId,name:typeof A==="string"?A:m.toProviderToolName(R.toolName),arguments:typeof U?.arguments==="string"?U.arguments:JSON.stringify(R.input)}),L.add(R.toolCallId)}else _.push({type:"function.call",tool_call_id:R.toolCallId,name:R.toolName,arguments:JSON.stringify(R.input)});break;case"tool-result":x(),v(R);break;default:throw new u({functionality:`assistant content type: ${R.type}`})}x();break}case"tool":for(let N of q.content){if(N.type==="tool-approval-response")continue;v(N)}}return{inputs:_,instructions:H.length>0?H.join(`
|
|
1
|
+
import{oe,Ie}from"./embed-hm6mmwpk.js";import{b,Ge,me,u,e,r,c,ie,o,t,l,f,y,i,n,G,k,T,d,j,M,ee,te,le,F,z,C,jt,he,W,Se,ct,a,s,h,g,ne,ve,S,O,I,D,p,E,Ce,Y}from"./embed-pm1dj76g.js";var xe=t({messages:o(G()).nullish(),cached_tokens:r().nullish(),audio_tokens:r().nullish()}).catchall(G()),Ue=t({reasoning_tokens:r().nullish()}).catchall(G()),_e=t({prompt_tokens:r(),completion_tokens:r(),total_tokens:r(),prompt_audio_seconds:r().nullish(),request_count:r().nullish(),service_tier:e().nullish(),num_cached_tokens:r().nullish(),prompt_tokens_details:xe.nullish(),prompt_token_details:xe.nullish(),completion_tokens_details:Ue.nullish()}).catchall(G());function pe(w){if(w==null)return te();let{prompt_tokens:m,completion_tokens:_}=w,H=w.num_cached_tokens??w.prompt_tokens_details?.cached_tokens??w.prompt_token_details?.cached_tokens??0;return{inputTokens:{total:m,noCache:m-H,cacheRead:H||void 0,cacheWrite:void 0},outputTokens:{total:_,text:_,reasoning:void 0},raw:w}}function ke({part:w}){if(w.data.type==="url")return w.data.url.toString();if(w.data.type==="data")return`data:${O({part:w})};base64,${M(w.data.data)}`;throw new u({functionality:`file part data type ${w.data.type}`})}function be(w){let m=[];for(let _=0;_<w.length;_++){let{role:H,content:L}=w[_],v=_===w.length-1;switch(H){case"system":m.push({role:"system",content:L});break;case"user":m.push({role:"user",content:L.map((q)=>{switch(q.type){case"text":return{type:"text",text:q.text};case"file":switch(q.data.type){case"reference":throw new u({functionality:"file parts with provider references"});case"text":throw new u({functionality:"text file parts"});case"url":case"data":if(z(q.mediaType)==="image")return{type:"image_url",image_url:ke({part:q})};else{if(q.data.type==="data"){if(O({part:q})!=="application/pdf")throw new u({functionality:"Only images and PDF file parts are supported"})}else if(q.mediaType!=="application/pdf")throw new u({functionality:"Only images and PDF file parts are supported"});return{type:"document_url",document_url:ke({part:q})}}}}})});break;case"assistant":{let q="",N=!1,x=[],R=[];for(let A of L)switch(A.type){case"text":q+=A.text,x.push({type:"text",text:A.text});break;case"tool-call":R.push({id:A.toolCallId,type:"function",function:{name:A.toolName,arguments:JSON.stringify(A.input)}});break;case"reasoning":N=!0,x.push({type:"thinking",thinking:[{type:"text",text:A.text}],closed:!0});break;default:throw Error(`Unsupported content type in assistant message: ${A.type}`)}m.push({role:"assistant",content:N?x:q,prefix:v?!0:void 0,tool_calls:R.length>0?R:void 0});break}case"tool":for(let q of L){if(q.type==="tool-approval-response")continue;let N=q.output,x;switch(N.type){case"text":case"error-text":x=N.value;break;case"execution-denied":x=N.reason??"Tool call execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(N.value)}m.push({role:"tool",name:q.toolName,tool_call_id:q.toolCallId,content:x})}break;default:throw Error(`Unsupported role: ${H}`)}}return m}function je(w){switch(w){case"stop":return"stop";case"length":case"model_length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"other"}}var Ee=()=>t({safePrompt:c().optional(),documentImageLimit:r().optional(),documentPageLimit:r().optional(),structuredOutputs:c().optional(),strictJsonSchema:c().optional(),parallelToolCalls:c().optional(),promptCacheKey:e().optional(),reasoningEffort:i(["high","none","low","max"]).optional()}),$e=a(()=>s(Ee())),De=a(()=>s(t({object:n("error"),message:e(),type:e(),param:e().nullable(),code:e().nullable()}))),ce=I({errorSchema:De,errorToMessage:(w)=>w.message});function Pe({tools:w,toolChoice:m}){w=w?.length?w:void 0;let _=[];if(w==null)return{tools:void 0,toolChoice:void 0,toolWarnings:_};let H=[];for(let v of w)if(v.type==="provider")_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`});else H.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:H,toolChoice:void 0,toolWarnings:_};let L=m.type;switch(L){case"auto":case"none":return{tools:H,toolChoice:L,toolWarnings:_};case"required":return{tools:H,toolChoice:"any",toolWarnings:_};case"tool":return{tools:H.filter((v)=>v.function.name===m.toolName),toolChoice:"any",toolWarnings:_};default:throw new u({functionality:`tool choice type: ${L}`})}}var Ve=new Set(["codestral-2508","codestral-latest","ministral-14b-2512","ministral-14b-latest","ministral-3b-2512","ministral-3b-latest","ministral-8b-2512","ministral-8b-latest","mistral-code-fim-latest","mistral-code-latest","mistral-large-latest","mistral-large-2512","voxtral-small-2507","voxtral-small-latest"]),Je=new Set(["zai-glm-5","zai-glm-5-3","zai-glm-5-3-flash","zai-glm-latest"]),ze=class w{static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.supportedUrls={"application/pdf":[/^https:\/\/.*$/]},this.modelId=m,this.config=_,this.generateId=_.generateId??C}get provider(){return this.config.provider}async getArgs({prompt:m,maxOutputTokens:_,temperature:H,topP:L,topK:v,frequencyPenalty:q,presencePenalty:N,reasoning:x,stopSequences:R,responseFormat:A,seed:U,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],V=await h({provider:"mistral",providerOptions:X,schema:$e})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=!Ve.has(this.modelId),K;if(re){let de=Je.has(this.modelId);if(V.reasoningEffort==null&&x==="none"&&de)Z.push({type:"compatibility",feature:"reasoning",details:'reasoning "none" is not directly supported by this model. mapped to effort "low".'});K=V.reasoningEffort??(W(x)?x==="none"?de?"low":"none":Se({reasoning:x,effortMap:de?{minimal:"low",low:"low",medium:"high",high:"high",xhigh:"max",max:"max"}:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},warnings:Z}):void 0)}else if(W(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let J=V.structuredOutputs??!0,P=V.strictJsonSchema??!1;if(A?.type==="json"&&(!J||A.schema==null))m=jt({messages:m,schema:A.schema});let B={model:this.modelId,safe_prompt:V.safePrompt,max_tokens:_,temperature:H,top_p:L,...q!=null?{frequency_penalty:q}:{},...N!=null?{presence_penalty:N}:{},stop:R,random_seed:U,reasoning_effort:K,response_format:A?.type==="json"?J&&A?.schema!=null?{type:"json_schema",json_schema:{schema:A.schema,strict:P,name:A.name??"response",description:A.description}}:{type:"json_object"}:void 0,document_image_limit:V.documentImageLimit,document_page_limit:V.documentPageLimit,...V.promptCacheKey!==void 0?{prompt_cache_key:V.promptCacheKey}:{},messages:be(m)},{tools:ae,toolChoice:fe,toolWarnings:ye}=Pe({tools:se,toolChoice:Q});return{args:{...B,tools:ae,tool_choice:fe,...ae!=null&&V.parallelToolCalls!==void 0?{parallel_tool_calls:V.parallelToolCalls}:{}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:H}=await this.getArgs(m),{responseHeaders:L,value:v,rawValue:q}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:_,failedResponseHandler:ce,successfulResponseHandler:p(Ke),abortSignal:m.abortSignal,fetch:this.config.fetch}),N=v.choices[0],x=[];if(N.message.content!=null&&Array.isArray(N.message.content)){for(let R of N.message.content)if(R.type==="thinking"){let A=Te(R.thinking);if(A.length>0)x.push({type:"reasoning",text:A})}else if(R.type==="text"){if(R.text.length>0)x.push({type:"text",text:R.text})}}else{let R=Me(N.message.content);if(R!=null&&R.length>0)x.push({type:"text",text:R})}if(N.message.tool_calls!=null)for(let R of N.message.tool_calls)x.push({type:"tool-call",toolCallId:R.id,toolName:R.function.name,input:R.function.arguments});return{content:x,finishReason:{unified:je(N.finish_reason),raw:N.finish_reason??void 0},usage:pe(v.usage),request:{body:_},response:{...ee(v),headers:L,body:q},warnings:H}}async doStream(m){let{args:_,warnings:H}=await this.getArgs(m),L={..._,stream:!0},{responseHeaders:v,value:q}=await g({url:`${this.config.baseURL}/chat/completions`,headers:d(this.config.headers?.(),m.headers),body:L,failedResponseHandler:ce,successfulResponseHandler:D(Be),abortSignal:m.abortSignal,fetch:this.config.fetch}),N={unified:"interrupted",raw:void 0},x=void 0,R=!0,A=!1,U=null,X,se=this.generateId;return{stream:q.pipeThrough(new TransformStream({start(Q){X=new Ce(Q,{generateId:se}),Q.enqueue({type:"stream-start",warnings:H})},transform(Q,Z){if(m.includeRawChunks)Z.enqueue({type:"raw",rawValue:Q.rawValue});if(!Q.success){N={unified:"error",raw:void 0},Z.enqueue({type:"error",error:Q.error});return}let V=Q.value;if(R)R=!1,Z.enqueue({type:"response-metadata",...ee(V)});if(V.usage!=null)x=V.usage;let re=V.choices[0],K=re.delta,J=Me(K.content);if(K.content!=null&&Array.isArray(K.content)){for(let P of K.content)if(P.type==="thinking"){let B=Te(P.thinking);if(B.length>0){if(U==null){if(A)Z.enqueue({type:"text-end",id:"0"}),A=!1;U=se(),Z.enqueue({type:"reasoning-start",id:U})}Z.enqueue({type:"reasoning-delta",id:U,delta:B})}}}if(J!=null&&J.length>0){if(!A){if(U!=null)Z.enqueue({type:"reasoning-end",id:U}),U=null;Z.enqueue({type:"text-start",id:"0"}),A=!0}Z.enqueue({type:"text-delta",id:"0",delta:J})}if(K?.tool_calls!=null)for(let P of K.tool_calls)X.processDelta(P);if(re.finish_reason!=null)N={unified:je(re.finish_reason),raw:re.finish_reason}},flush(Q){if(U!=null)Q.enqueue({type:"reasoning-end",id:U});if(A)Q.enqueue({type:"text-end",id:"0"});X.flush(),Q.enqueue({type:"finish",finishReason:N,usage:pe(x)})}})),request:{body:L},response:{headers:v}}}};function Te(w){return w.filter((m)=>m.type==="text").map((m)=>m.text).join("")}function Me(w){if(typeof w==="string")return w;if(w==null)return;let m=[];for(let _ of w){let{type:H}=_;switch(H){case"text":m.push(_.text);break;case"thinking":case"image_url":case"reference":break;default:throw Error(`Unsupported type: ${H}`)}}return m.length?m.join(""):void 0}var qe=()=>l([e(),o(f("type",[t({type:n("text"),text:e()}),t({type:n("image_url"),image_url:l([e(),t({url:e(),detail:e().nullable()})])}),t({type:n("reference"),reference_ids:o(l([e(),r()]))}),t({type:n("thinking"),thinking:o(t({type:n("text"),text:e()}))})]))]).nullish(),Ke=a(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({message:t({role:n("assistant"),content:qe(),tool_calls:o(t({id:e(),function:t({name:e(),arguments:e()})})).nullish()}),index:r(),finish_reason:e().nullish()})),object:n("chat.completion"),usage:_e}))),Be=a(()=>s(t({id:e().nullish(),created:r().nullish(),model:e().nullish(),choices:o(t({delta:t({role:i(["assistant"]).optional(),content:qe(),tool_calls:o(t({index:r().nullish(),id:e().nullish(),function:t({name:e().nullish(),arguments:e().nullish()})})).nullish()}),finish_reason:e().nullish(),index:r()})),usage:_e.nullish()})));function We(w,m){let _=[],H=[],L=new Set,v=(q)=>{if(L.has(q.toolCallId)){let x=null;if(q.output.type==="json"){let R=q.output.value,A=R!=null&&typeof R==="object"&&"info"in R?R.info:void 0;if(A!=null&&typeof A==="object"&&!Array.isArray(A))x="result"in A?A.result??A:A}_.push({type:"function.result",tool_call_id:q.toolCallId,result:typeof x==="string"?x:JSON.stringify(x)});return}let N=be([{role:"tool",content:[q]}])[0];_.push({type:"function.result",tool_call_id:q.toolCallId,result:N.content})};for(let q of w)switch(q.role){case"system":H.push(q.content);break;case"user":{let N=be([q])[0];if(N.role==="user")_.push({type:"message.input",role:"user",content:N.content});break}case"assistant":{let N=[],x=()=>{if(N.length>0)_.push({type:"message.input",role:"assistant",content:N}),N=[]};for(let R of q.content)switch(R.type){case"text":N.push({type:"text",text:R.text});break;case"reasoning":N.push({type:"thinking",thinking:[{type:"text",text:R.text}],closed:!0});break;case"tool-call":if(x(),R.providerExecuted){let A=R.providerOptions?.mistral?.function??R.providerOptions?.mistral?.name,U=R.input;_.push({type:"function.call",tool_call_id:R.toolCallId,name:typeof A==="string"?A:m.toProviderToolName(R.toolName),arguments:typeof U?.arguments==="string"?U.arguments:JSON.stringify(R.input)}),L.add(R.toolCallId)}else _.push({type:"function.call",tool_call_id:R.toolCallId,name:R.toolName,arguments:JSON.stringify(R.input)});break;case"tool-result":x(),v(R);break;default:throw new u({functionality:`assistant content type: ${R.type}`})}x();break}case"tool":for(let N of q.content){if(N.type==="tool-approval-response")continue;v(N)}}return{inputs:_,instructions:H.length>0?H.join(`
|
|
2
2
|
|
|
3
3
|
`):void 0}}var Fe=a(()=>s(Ee())),ge={"mistral.web_search":"web_search","mistral.web_search_premium":"web_search_premium"};function Ze({tools:w,toolChoice:m}){w=w?.length?w:void 0;let _=[];if(w==null)return{tools:void 0,toolChoice:void 0,toolWarnings:_};let H=[];for(let v of w)if(v.type==="provider"){if(v.id==="mistral.web_search"||v.id==="mistral.web_search_premium"){H.push({type:ge[v.id]});continue}_.push({type:"unsupported",feature:`provider-defined tool ${v.id}`})}else H.push({type:"function",function:{name:v.name,description:v.description,parameters:v.inputSchema,...v.strict!=null?{strict:v.strict}:{}}});if(m==null)return{tools:H,toolChoice:void 0,toolWarnings:_};let L=m.type;switch(L){case"auto":case"none":return{tools:H,toolChoice:L,toolWarnings:_};case"required":return{tools:H,toolChoice:"any",toolWarnings:_};case"tool":{let v=le({tools:w,providerToolNames:ge}).toProviderToolName(m.toolName);return{tools:H.filter((q)=>q.type==="function"?q.function.name===v:q.type===v),toolChoice:"any",toolWarnings:_}}default:throw new u({functionality:`tool choice type: ${L}`})}}var Ye=new Set(["glm-5-2","labs-leanstral-1-5","labs-leanstral-1-5-1","magistral-medium-latest","magistral-small-latest","mistral-large-4","mistral-large-4-0","mistral-medium","mistral-medium-2604","mistral-medium-3","mistral-medium-3-5","mistral-medium-3.5","mistral-medium-latest","mistral-small-2603","mistral-small-latest","mistral-vibe-cli-fast","mistral-vibe-cli-latest","mistral-vibe-cli-with-tools","zai-glm-5-2"]),Qe=class w{static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.supportedUrls={"application/pdf":[/^https:\/\/.*$/]},this.modelId=m,this.config=_,this.generateId=_.generateId??C}get provider(){return this.config.provider}async getArgs({prompt:m,maxOutputTokens:_,temperature:H,topP:L,topK:v,frequencyPenalty:q,presencePenalty:N,reasoning:x,stopSequences:R,responseFormat:A,seed:U,providerOptions:X,tools:se,toolChoice:Q}){let Z=[],V=await h({provider:"mistral",providerOptions:X,schema:Fe})??{};if(v!=null)Z.push({type:"unsupported",feature:"topK"});let re=Ye.has(this.modelId),K;if(re)K=V.reasoningEffort??(W(x)?x==="none"?"none":Se({reasoning:x,effortMap:{minimal:"high",low:"high",medium:"high",high:"high",xhigh:"high",max:"high"},warnings:Z}):void 0);else if(W(x))Z.push({type:"unsupported",feature:"reasoning",details:"This model does not support reasoning configuration."});let J=V.structuredOutputs??!0,P=V.strictJsonSchema??!1;if(A?.type==="json"&&(!J||A.schema==null))m=jt({messages:m,schema:A.schema});let B={max_tokens:_,temperature:H,top_p:L,...q!=null?{frequency_penalty:q}:{},...N!=null?{presence_penalty:N}:{},stop:R,random_seed:U,reasoning_effort:K,response_format:A?.type==="json"?J&&A?.schema!=null?{type:"json_schema",json_schema:{schema:A.schema,strict:P,name:A.name??"response",description:A.description}}:{type:"json_object"}:void 0},{tools:ae,toolChoice:fe,toolWarnings:ye}=Ze({tools:se,toolChoice:Q});for(let[de,He]of Object.entries({safePrompt:V.safePrompt,documentImageLimit:V.documentImageLimit,documentPageLimit:V.documentPageLimit,promptCacheKey:V.promptCacheKey,parallelToolCalls:V.parallelToolCalls}))if(He!=null)Z.push({type:"unsupported",feature:de,details:"Not supported by the Mistral Conversations API."});return{args:{model:this.modelId,store:!1,...We(m,le({tools:se,providerToolNames:ge})),tools:ae,completion_args:{...B,tool_choice:fe}},warnings:[...Z,...ye]}}async doGenerate(m){let{args:_,warnings:H}=await this.getArgs(m),{value:L,rawValue:v,responseHeaders:q}=await g({url:`${this.config.baseURL}/conversations`,headers:d(this.config.headers?.(),m.headers),body:_,failedResponseHandler:ce,successfulResponseHandler:p(nt),abortSignal:m.abortSignal,fetch:this.config.fetch}),N=Re({tools:m.tools,generateId:this.generateId}),x=[],R=!1,A;for(let U of L.outputs)switch(U.type){case"tool.execution":x.push(...N.convertTool(U));break;case"function.call":R=!0,x.push({type:"tool-call",toolCallId:U.tool_call_id,toolName:U.name,input:typeof U.arguments==="string"?U.arguments:JSON.stringify(U.arguments)});break;case"message.output":A=U.model??A;for(let X of typeof U.content==="string"?[{type:"text",text:U.content}]:U.content)x.push(...N.convertChunk(X))}return{content:x,finishReason:{unified:R?"tool-calls":"stop",raw:void 0},usage:pe(L.usage),request:{body:_},response:{id:L.conversation_id,modelId:A,headers:q,body:v},warnings:H}}async doStream(m){let{args:_,warnings:H}=await this.getArgs(m),L={..._,stream:!0},{value:v,responseHeaders:q}=await g({url:`${this.config.baseURL}/conversations`,headers:d(this.config.headers?.(),m.headers),body:L,failedResponseHandler:ce,successfulResponseHandler:D(st),abortSignal:m.abortSignal,fetch:this.config.fetch}),N=Re({tools:m.tools,generateId:this.generateId}),x=new Map,R,A,U,X=!1,se=!1,Q=!1,Z=!1,V=(K)=>{if(A!=null)K.enqueue({type:A.type==="text"?"text-end":"reasoning-end",id:A.id}),A=void 0},re=this.generateId;return{stream:v.pipeThrough(new TransformStream({start(K){R=new Ce(K,{generateId:re}),K.enqueue({type:"stream-start",warnings:H})},transform(K,J){if(m.includeRawChunks)J.enqueue({type:"raw",rawValue:K.rawValue});if(!K.success){se=!0,J.enqueue({type:"error",error:K.error});return}let P=K.value;switch(P.type){case"conversation.response.started":J.enqueue({type:"response-metadata",id:P.conversation_id,...P.created_at!=null?{timestamp:new Date(P.created_at)}:{}});break;case"conversation.response.done":U=P.usage??void 0,Q=!0;break;case"conversation.response.error":se=!0,J.enqueue({type:"error",error:P});break;case"message.output.delta":if(!Z&&P.model!=null)Z=!0,J.enqueue({type:"response-metadata",modelId:P.model});for(let B of N.convertChunk(typeof P.content==="string"?{type:"text",text:P.content}:P.content))if(B.type==="text"||B.type==="reasoning"){let ae=`${P.id}-${P.content_index??0}`;if(A?.id!==ae||A.type!==B.type)V(J),A={id:ae,type:B.type},J.enqueue({type:B.type==="text"?"text-start":"reasoning-start",id:ae});J.enqueue({type:B.type==="text"?"text-delta":"reasoning-delta",id:ae,delta:B.text})}else if(B.type==="source")J.enqueue(B);break;case"function.call.delta":V(J),X=!0,R.processDelta({id:P.tool_call_id,index:P.output_index,function:{name:P.name,arguments:P.arguments}});break;case"tool.execution.started":case"tool.execution.delta":{V(J);let B=x.get(P.id);if(B==null)x.set(P.id,{name:P.name,arguments:P.arguments,function:P.function}),J.enqueue({type:"tool-input-start",id:P.id,toolName:N.toolNameMapping.toCustomToolName(P.name),providerExecuted:!0});else B.arguments+=P.arguments;break}case"tool.execution.done":{let B=x.get(P.id);if(B==null){se=!0,J.enqueue({type:"error",error:Error(`Missing tool execution start for ${P.id}`)});break}J.enqueue({type:"tool-input-delta",id:P.id,delta:JSON.stringify({arguments:B.arguments})}),J.enqueue({type:"tool-input-end",id:P.id});for(let ae of N.convertTool({type:"tool.execution",id:P.id,name:B.name,arguments:B.arguments,function:P.function??B.function,info:P.info}))J.enqueue(ae);x.delete(P.id);break}}},flush(K){V(K),R.flush(),K.enqueue({type:"finish",finishReason:{unified:se||!Q||x.size>0?"error":X?"tool-calls":"stop",raw:void 0},usage:pe(U)})}})),request:{body:L},response:{headers:q}}}};function Re({tools:w,generateId:m}){let _=le({tools:w,providerToolNames:ge}),H=new Set;return{toolNameMapping:_,convertChunk(L){switch(L.type){case"text":return L.text.length>0?[{type:"text",text:L.text}]:[];case"thinking":{let q=L.thinking.map((N)=>N.text).join("");return q.length>0?[{type:"reasoning",text:q}]:[]}case"tool_reference":if(L.url==null||H.has(L.url))return[];let v=m();return H.add(L.url),[{type:"source",sourceType:"url",id:v,url:L.url,title:L.title??L.url}]}},convertTool(L){let v=_.toCustomToolName(L.name);return[{type:"tool-call",toolCallId:L.id,toolName:v,input:JSON.stringify({arguments:L.arguments}),providerExecuted:!0,providerMetadata:{mistral:{type:"tool.execution",name:L.name,...L.function!=null?{function:L.function}:{}}}},{type:"tool-result",toolCallId:L.id,toolName:v,result:{...L.info!=null?{info:L.info}:{}}}]}}}var Oe=()=>f("type",[t({type:n("text"),text:e()}),t({type:n("thinking"),thinking:o(t({type:n("text"),text:e()}))}),t({type:n("tool_reference"),tool:e().nullish(),title:e().nullish(),url:e().nullish()})]),Xe=()=>l([e(),o(Oe())]),et=()=>t({type:n("tool.execution"),id:e(),name:e(),arguments:e(),function:e().nullish(),info:y(e(),G()).nullish()}),tt=()=>t({type:n("function.call"),tool_call_id:e(),name:e(),arguments:l([e(),y(e(),G())])}),Le=()=>_e.extend({prompt_tokens:r().default(0),completion_tokens:r().default(0),total_tokens:r().default(0)}),nt=a(()=>s(t({conversation_id:e(),outputs:o(f("type",[et(),tt(),t({type:n("message.output"),content:Xe(),model:e().nullish()})])),usage:Le().nullish()}))),st=a(()=>s(f("type",[t({type:n("conversation.response.started"),conversation_id:e(),created_at:e().nullish()}),t({type:n("conversation.response.done"),usage:Le().nullish()}),t({type:n("conversation.response.error"),message:e(),code:r()}),t({type:n("message.output.delta"),id:e(),content_index:r().nullish(),content:l([e(),Oe()]),model:e().nullish()}),t({type:n("function.call.delta"),tool_call_id:e(),name:e(),arguments:e(),output_index:r().nullish()}),t({type:i(["tool.execution.started","tool.execution.delta"]),id:e(),name:e(),arguments:e(),function:e().nullish()}),t({type:n("tool.execution.done"),id:e(),name:e(),function:e().nullish(),info:y(e(),G()).nullish()})]))),ot=t({metadata:y(e(),ie()).optional(),outputDimension:r().int().positive().optional(),outputDtype:i(["float","int8","uint8","binary","ubinary"]).optional()}),at=class w{get provider(){return this.config.provider}static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](m){return new w(m.modelId,m.config)}constructor(m,_){this.specificationVersion="v4",this.maxEmbeddingsPerCall=32,this.supportsParallelCalls=!1,this.modelId=m,this.config=_}async doEmbed({values:m,dimensions:_,abortSignal:H,headers:L,providerOptions:v}){if(m.length>this.maxEmbeddingsPerCall)throw new me({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:m});let q=await h({provider:"mistral",providerOptions:v,schema:ot})??{},{responseHeaders:N,value:x,rawValue:R}=await g({url:`${this.config.baseURL}/embeddings`,headers:d(this.config.headers?.(),L),body:{model:this.modelId,input:m,metadata:q.metadata,output_dimension:q.outputDimension??_,output_dtype:q.outputDtype,encoding_format:"float"},failedResponseHandler:ce,successfulResponseHandler:p(it),abortSignal:H,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map((A)=>A.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:N,body:R}}}},it=a(()=>s(t({data:o(t({embedding:o(r())})),usage:t({prompt_tokens:r()}).nullish()}))),rt=a(()=>s(t({refAudio:e().min(1).optional(),expressiveness:r().min(1).max(5).optional(),phonemeHints:y(e().min(1),o(e().min(1)).min(1)).optional()}))),lt=class w{static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](m){return new w(m.modelId,m.config)}get provider(){return this.config.provider}constructor(m,_){this.modelId=m,this.config=_,this.specificationVersion="v4"}async getArgs({text:m,voice:_,outputFormat:H="mp3",instructions:L,speed:v,language:q,providerOptions:N}){let x=[],R=await h({provider:"mistral",providerOptions:N,schema:rt}),A="mp3";if(["pcm","wav","mp3","flac","opus"].includes(H))A=H;else x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${H}. Using mp3 instead.`});if(L!=null)x.push({type:"unsupported",feature:"instructions",details:"Mistral speech models do not support the `instructions` option. Use a reference audio clip to guide delivery."});if(v!=null)x.push({type:"unsupported",feature:"speed",details:"Mistral speech models do not support the `speed` option. It was ignored."});if(q!=null)x.push({type:"unsupported",feature:"language",details:"Mistral speech models do not support the `language` option. Language is inferred from the input text and voice."});let U=R?.refAudio,X={model:this.modelId,input:m,voice_id:U==null?_:void 0,ref_audio:U,expressiveness:R?.expressiveness,phoneme_hints:R?.phonemeHints,response_format:A,stream:!1};return{requestBody:X,requestBodyValues:{...X,ref_audio:U==null?void 0:"[redacted]"},warnings:x}}async doGenerate(m){let _=this.config._internal?.currentDate?.()??new Date,{requestBody:H,requestBodyValues:L,warnings:v}=await this.getArgs(m),{value:q,responseHeaders:N,rawValue:x}=await ve({url:`${this.config.baseURL}/audio/speech`,headers:d({"Content-Type":"application/json"},this.config.headers?.(),m.headers),body:{content:JSON.stringify(H),values:L},failedResponseHandler:ce,successfulResponseHandler:p(ut),abortSignal:m.abortSignal,fetch:this.config.fetch});return{audio:q.audio_data,warnings:v,request:{body:JSON.stringify(L)},response:{timestamp:_,modelId:this.modelId,headers:N,body:x}}}},ut=a(()=>s(t({audio_data:e()}))),dt=a(()=>s(t({language:e().min(1).optional(),returnLanguage:c().optional(),temperature:r().optional(),timestampGranularities:o(i(["segment","word"])).min(1).optional(),diarize:c().optional(),contextBias:o(e().min(1)).optional()}))),pt=class w{static[k](m){return E({modelId:m.modelId,config:m.config})}static[T](m){return new w(m.modelId,m.config)}get provider(){return this.config.provider}constructor(m,_){this.modelId=m,this.config=_,this.specificationVersion="v4"}async getArgs({audio:m,mediaType:_,providerOptions:H}){let L=[],v=await h({provider:"mistral",providerOptions:H,schema:dt});if(["voxtral-mini-2507","voxtral-mini-2602","voxtral-mini-latest"].includes(this.modelId)&&v?.language!=null&&v.timestampGranularities!=null)throw new b({argument:"providerOptions",message:"providerOptions.mistral.language cannot be combined with providerOptions.mistral.timestampGranularities"});if(v?.language!=null&&v.returnLanguage)throw new b({argument:"providerOptions",message:"providerOptions.mistral.language cannot be combined with providerOptions.mistral.returnLanguage"});let q=new FormData,N=m instanceof Uint8Array?new Blob([m]):new Blob([j(m)]);if(q.append("model",this.modelId),q.append("file",new File([N],"audio",{type:_}),`audio.${ct(_)}`),v!=null)ue(q,"language",v.language),ue(q,"return_language",v.returnLanguage),ue(q,"temperature",v.temperature),ue(q,"timestamp_granularities",v.timestampGranularities),ue(q,"diarize",v.diarize),ue(q,"context_bias",v.contextBias);return{formData:q,warnings:L}}async doGenerate(m){let _=this.config._internal?.currentDate?.()??new Date,{formData:H,warnings:L}=await this.getArgs(m),{value:v,responseHeaders:q,rawValue:N}=await ne({url:`${this.config.baseURL}/audio/transcriptions`,headers:d(this.config.headers?.(),m.headers),formData:H,failedResponseHandler:ce,successfulResponseHandler:p(mt),abortSignal:m.abortSignal,fetch:this.config.fetch}),x=v.segments?.map((U)=>({text:U.text,startSecond:U.start,endSecond:U.end}))??[],R={};if(v.usage!=null)R.usage={...v.usage.prompt_tokens!=null&&{promptTokens:v.usage.prompt_tokens},...v.usage.completion_tokens!=null&&{completionTokens:v.usage.completion_tokens},...v.usage.total_tokens!=null&&{totalTokens:v.usage.total_tokens},...v.usage.prompt_audio_seconds!=null&&{promptAudioSeconds:v.usage.prompt_audio_seconds},...v.usage.request_count!=null&&{requestCount:v.usage.request_count}};let A=v.segments?.filter((U)=>U.type!=null||U.score!=null||U.speaker_id!=null).map((U)=>({text:U.text,startSecond:U.start,endSecond:U.end,...U.type!=null&&{type:U.type},...U.score!=null&&{score:U.score},...U.speaker_id!=null&&{speakerId:U.speaker_id}}));if(A!=null&&A.length>0)R.segments=A;return{text:v.text,segments:x,language:v.language??void 0,durationInSeconds:v.usage?.prompt_audio_seconds??x.at(-1)?.endSecond??void 0,warnings:L,...v.usage!=null&&{usage:v.usage},response:{timestamp:_,modelId:v.model,headers:q,body:N},...Object.keys(R).length>0&&{providerMetadata:{mistral:R}}}}};function ue(w,m,_){if(_==null)return;if(Array.isArray(_)){for(let H of _)w.append(m,H);return}w.append(m,String(_))}var mt=a(()=>s(t({model:e(),text:e(),language:e().nullish(),segments:o(t({type:n("transcription_segment").nullish(),text:e(),start:r(),end:r(),score:r().nullish(),speaker_id:e().nullish()})).nullish(),usage:t({prompt_tokens:r().nullish(),completion_tokens:r().nullish(),total_tokens:r().nullish(),prompt_audio_seconds:r().nullish(),request_count:r().nullish()}).nullish()}))),gt="4.0.74",Ae=a(()=>s(t({arguments:e()}))),Ne=a(()=>s(t({info:y(e(),G()).optional()}))),ht=S({id:"mistral.web_search",inputSchema:Ae,outputSchema:Ne}),ft=S({id:"mistral.web_search_premium",inputSchema:Ae,outputSchema:Ne}),yt=(w={})=>ht(w),bt=(w={})=>ft(w),vt={webSearch:yt,webSearchPremium:bt};function we(w={}){let m=Y(w.baseURL)??"https://api.mistral.ai/v1",_=()=>F({Authorization:`Bearer ${he({apiKey:w.apiKey,environmentVariableName:"MISTRAL_API_KEY",description:"Mistral"})}`,...w.headers},`ai-sdk-mistral/${gt}`),H=(R)=>new ze(R,{provider:"mistral.chat",baseURL:m,headers:_,fetch:w.fetch,generateId:w.generateId}),L=(R)=>new at(R,{provider:"mistral.embedding",baseURL:m,headers:_,fetch:w.fetch}),v=(R)=>new Qe(R,{provider:"mistral.conversation",baseURL:m,headers:_,fetch:w.fetch,generateId:w.generateId}),q=(R)=>new lt(R,{provider:"mistral.speech",baseURL:m,headers:_,fetch:w.fetch}),N=(R)=>new pt(R,{provider:"mistral.transcription",baseURL:m,headers:_,fetch:w.fetch}),x=function(R){if(new.target)throw Error("The Mistral model function cannot be called with the new keyword.");return H(R)};return x.specificationVersion="v4",x.languageModel=H,x.chat=H,x.conversation=v,x.tools=vt,x.embedding=L,x.embeddingModel=L,x.textEmbedding=L,x.textEmbeddingModel=L,x.speech=q,x.speechModel=q,x.transcription=N,x.transcriptionModel=N,x.imageModel=(R)=>{throw new Ge({modelId:R,modelType:"imageModel"})},x}var St=we();var _t=Ie(we);function Rt(){oe("mistral",_t)}export{Rt as register};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{St}from"./embed-gx1epk52.js";import{Ct}from"./embed-strrtkwa.js";import{Ye,zt,Dt,Xe,et,Bt,Ut}from"./embed-b072jtkd.js";function x(e,i){let t=[...i].reverse().find((s)=>s.role==="user");return Ye(e)<12&&t?`${t.content} ${e}`:e}var M=/^(?:hello|hi|hey|hiya|yo|hola|bonjour|bonsoir|salut|coucou|good (?:morning|afternoon|evening)|merci(?: beaucoup| bien)?|thanks?(?: you| a lot)?|thx|ok(?:ay)?|d accord|cool|super|parfait|great|nice|bye|goodbye|au revoir|ciao)(?: (?:murmur|there|toi|you|à toi))?$/;function v(e){return M.test(e.toLowerCase().replace(/[\p{P}\p{S}\s]+/gu," ").trim())}function L(e){let i=e.retriever??(e.index?Ct(e.index):null)??(()=>{throw Error("murmur: pass `index` or `retriever`.")})();return{retriever:i,async ask(t,{history:s=[],signal:u}={}){let a={};if(e.limit!==void 0)a.limit=e.limit;if(e.budgetTokens!==void 0)a.budgetTokens=e.budgetTokens;let c=v(t),n=c?[]:await i.search(x(t,s),a),d=[e.instructions?.trim(),Dt(e.language),c?"The visitor is only greeting or thanking you: answer in one short, friendly sentence and invite a question about this site. Cite nothing.":n.length?`Sources:
|
|
2
|
+
|
|
3
|
+
${zt(n)}`:"Sources: none matched this question. Say you could not find it on this site."].filter(Boolean).join(`
|
|
4
|
+
|
|
5
|
+
`),y=[...s.slice(-(e.historyTurns??6)*2).map((r)=>({role:r.role,content:r.role==="assistant"?Bt(r.content):r.content})),{role:"user",content:t}],f=typeof e.model==="function"?await e.model():e.model,h=St({model:f,instructions:d,messages:y,onError:()=>{},...u?{abortSignal:u}:{}}),o="",l=()=>{},m=()=>{},g=new Promise((r,p)=>{l=r,m=p});g.catch(()=>{});async function*b(){try{for await(let r of h.stream){if(r.type==="error")throw r.error;if(r.type!=="text-delta")continue;o+=r.text,yield r.text}o=et(Xe(o),n.length),l({text:o,cited:Ut(o,n.length)})}catch(r){throw m(r),r}}return{passages:n,textStream:b(),done:g}}}}export{L as createMurmur};
|