@mcp-use/inspector 0.4.13 → 0.5.0-canary.1

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.
Files changed (35) hide show
  1. package/dist/cli.js +1 -5
  2. package/dist/client/assets/{chunk-VL2OQCWN-C61KfPSl.js → chunk-VL2OQCWN-MBqdQwvw.js} +1 -1
  3. package/dist/client/assets/{embeddings-BIo-kwlO.js → embeddings-B5Be4aCe.js} +1 -1
  4. package/dist/client/assets/index-B_wEtYs8.js +40 -0
  5. package/dist/client/assets/index-Bn0J9w6n.js +1438 -0
  6. package/dist/client/assets/{index-dXj4eNzX.js → index-BrE2Q7Md.js} +1 -1
  7. package/dist/client/assets/index-Bx3FWJNp.css +1 -0
  8. package/dist/client/assets/{index-jQGzGE29.js → index-CiA4rdQm.js} +9 -13
  9. package/dist/client/assets/index-CjCfkF26.js +2 -0
  10. package/dist/client/assets/{index-D1RB_-JK.js → index-DyE3WIut.js} +1 -1
  11. package/dist/client/assets/{index-Cva-hqGs.js → index-poirZU-_.js} +1 -1
  12. package/dist/client/assets/langfuse-C4HKZ3NL-DD548jIo.js +562 -0
  13. package/dist/client/assets/{winston-B9dQmIAy.js → winston-vzZ2qSTo.js} +29 -34
  14. package/dist/client/index.html +3 -3
  15. package/dist/server/{chunk-TIYOH5C4.js → chunk-37X7HLUV.js} +1 -5
  16. package/dist/server/{chunk-ZFMPIRVB.js → chunk-5OMSQNKB.js} +1 -1
  17. package/dist/server/{chunk-YGCKPAWJ.js → chunk-UZO6G7KA.js} +3 -3
  18. package/dist/server/{chunk-76XNP4ZB.js → chunk-VOQ3DLXM.js} +1 -5
  19. package/dist/server/{chunk-222XA5JA.js → chunk-WYBXXYSP.js} +1 -1
  20. package/dist/server/cli.js +4 -4
  21. package/dist/server/index.js +5 -5
  22. package/dist/server/middleware.js +5 -5
  23. package/dist/server/server.js +4 -4
  24. package/dist/server/shared-routes.js +2 -2
  25. package/dist/server/shared-static.js +2 -2
  26. package/dist/server/shared-utils-browser.d.ts.map +1 -1
  27. package/dist/server/shared-utils-browser.js +1 -1
  28. package/dist/server/shared-utils.d.ts.map +1 -1
  29. package/dist/server/shared-utils.js +1 -1
  30. package/package.json +2 -2
  31. package/dist/client/assets/index-BLLgp4UX.js +0 -1734
  32. package/dist/client/assets/index-BrUPorMz.css +0 -1
  33. package/dist/client/assets/index-g0U2Uz9F.js +0 -40
  34. package/dist/client/assets/index-gQstsvsJ.js +0 -212
  35. package/dist/client/assets/langfuse-C4HKZ3NL-ComM_afA.js +0 -570
@@ -1,212 +0,0 @@
1
- import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g as se,h as ie,j as _e,k as Ee,p as A,B as ve,l as we,O as Te,m as Ie,n as Oe,J as Re,R as D,o as Se}from"./index-jQGzGE29.js";import{v as ae}from"./index-BLLgp4UX.js";import"./embeddings-BIo-kwlO.js";import"./chunk-VL2OQCWN-C61KfPSl.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(ne(e)?fe(e):e),{$schema:t,...o}=n;return o}function Ae(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return Ce.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>oe(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(_e(e))return Ee(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(ye(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),oe(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!he(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new pe({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new ge({text:c,message:new me({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(se(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return ie(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Ae(n.function.parameters)}:n})}]}var U=class extends ve{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await we(this.zodSchema,e);if(n.success)return n.data;throw new Te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));/**
2
- * @license
3
- * Copyright 2024 Google LLC
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));/**
17
- * @license
18
- * Copyright 2024 Google LLC
19
- *
20
- * Licensed under the Apache License, Version 2.0 (the "License");
21
- * you may not use this file except in compliance with the License.
22
- * You may obtain a copy of the License at
23
- *
24
- * http://www.apache.org/licenses/LICENSE-2.0
25
- *
26
- * Unless required by applicable law or agreed to in writing, software
27
- * distributed under the License is distributed on an "AS IS" BASIS,
28
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29
- * See the License for the specific language governing permissions and
30
- * limitations under the License.
31
- */const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));/**
32
- * @license
33
- * Copyright 2024 Google LLC
34
- *
35
- * Licensed under the Apache License, Version 2.0 (the "License");
36
- * you may not use this file except in compliance with the License.
37
- * You may obtain a copy of the License at
38
- *
39
- * http://www.apache.org/licenses/LICENSE-2.0
40
- *
41
- * Unless required by applicable law or agreed to in writing, software
42
- * distributed under the License is distributed on an "AS IS" BASIS,
43
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44
- * See the License for the specific language governing permissions and
45
- * limitations under the License.
46
- */class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}/**
47
- * @license
48
- * Copyright 2024 Google LLC
49
- *
50
- * Licensed under the Apache License, Version 2.0 (the "License");
51
- * you may not use this file except in compliance with the License.
52
- * You may obtain a copy of the License at
53
- *
54
- * http://www.apache.org/licenses/LICENSE-2.0
55
- *
56
- * Unless required by applicable law or agreed to in writing, software
57
- * distributed under the License is distributed on an "AS IS" BASIS,
58
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
59
- * See the License for the specific language governing permissions and
60
- * limitations under the License.
61
- */const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}/**
62
- * @license
63
- * Copyright 2024 Google LLC
64
- *
65
- * Licensed under the Apache License, Version 2.0 (the "License");
66
- * you may not use this file except in compliance with the License.
67
- * You may obtain a copy of the License at
68
- *
69
- * http://www.apache.org/licenses/LICENSE-2.0
70
- *
71
- * Unless required by applicable law or agreed to in writing, software
72
- * distributed under the License is distributed on an "AS IS" BASIS,
73
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
74
- * See the License for the specific language governing permissions and
75
- * limitations under the License.
76
- */function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
77
- `+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function S(e){return!!e.finishReason&&Xe.includes(e.finishReason)}function C(e){var n,t,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((n=e.promptFeedback)===null||n===void 0)&&n.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((t=e.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];S(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function I(e){return this instanceof I?(this.v=e,this):new I(e)}function Qe(e,n,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(e,n||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(d){o[d]&&(s[d]=function(l){return new Promise(function(h,m){i.push([d,l,h,m])>1||c(d,l)})})}function c(d,l){try{u(o[d](l))}catch(h){f(i[0][3],h)}}function u(d){d.value instanceof I?Promise.resolve(d.value.v).then(r,p):f(i[0][2],d)}function r(d){c("next",d)}function p(d){c("throw",d)}function f(d,l){d(l),i.shift(),i.length&&c(i[0][0],i[0][1])}}/**
78
- * @license
79
- * Copyright 2024 Google LLC
80
- *
81
- * Licensed under the Apache License, Version 2.0 (the "License");
82
- * you may not use this file except in compliance with the License.
83
- * You may obtain a copy of the License at
84
- *
85
- * http://www.apache.org/licenses/LICENSE-2.0
86
- *
87
- * Unless required by applicable law or agreed to in writing, software
88
- * distributed under the License is distributed on an "AS IS" BASIS,
89
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
90
- * See the License for the specific language governing permissions and
91
- * limitations under the License.
92
- */const V=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Ze(e){const n=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=nt(n),[o,s]=t.tee();return{stream:tt(o),response:et(s)}}async function et(e){const n=[],t=e.getReader();for(;;){const{done:o,value:s}=await t.read();if(o)return b(ot(n));n.push(s)}}function tt(e){return Qe(this,arguments,function*(){const t=e.getReader();for(;;){const{value:o,done:s}=yield I(t.read());if(s)break;yield yield I(b(o))}})}function nt(e){const n=e.getReader();return new ReadableStream({start(o){let s="";return i();function i(){return n.read().then(({value:a,done:c})=>{if(c){if(s.trim()){o.error(new g("Failed to parse stream"));return}o.close();return}s+=a;let u=s.match(V),r;for(;u;){try{r=JSON.parse(u[1])}catch{o.error(new g(`Error parsing JSON response: "${u[1]}"`));return}o.enqueue(r),s=s.substring(u[0].length),u=s.match(V)}return i()}).catch(a=>{let c=a;throw c.stack=a.stack,c.name==="AbortError"?c=new ce("Request aborted when reading from the stream"):c=new g("Error reading from the stream"),c})}}})}function ot(e){const n=e[e.length-1],t={promptFeedback:n?.promptFeedback};for(const o of e){if(o.candidates){let s=0;for(const i of o.candidates)if(t.candidates||(t.candidates=[]),t.candidates[s]||(t.candidates[s]={index:s}),t.candidates[s].citationMetadata=i.citationMetadata,t.candidates[s].groundingMetadata=i.groundingMetadata,t.candidates[s].finishReason=i.finishReason,t.candidates[s].finishMessage=i.finishMessage,t.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){t.candidates[s].content||(t.candidates[s].content={role:i.content.role||"user",parts:[]});const a={};for(const c of i.content.parts)c.text&&(a.text=c.text),c.functionCall&&(a.functionCall=c.functionCall),c.executableCode&&(a.executableCode=c.executableCode),c.codeExecutionResult&&(a.codeExecutionResult=c.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),t.candidates[s].content.parts.push(a)}s++}o.usageMetadata&&(t.usageMetadata=o.usageMetadata)}return t}/**
93
- * @license
94
- * Copyright 2024 Google LLC
95
- *
96
- * Licensed under the Apache License, Version 2.0 (the "License");
97
- * you may not use this file except in compliance with the License.
98
- * You may obtain a copy of the License at
99
- *
100
- * http://www.apache.org/licenses/LICENSE-2.0
101
- *
102
- * Unless required by applicable law or agreed to in writing, software
103
- * distributed under the License is distributed on an "AS IS" BASIS,
104
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
105
- * See the License for the specific language governing permissions and
106
- * limitations under the License.
107
- */async function le(e,n,t,o){const s=await R(n,E.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(t),o);return Ze(s)}async function ue(e,n,t,o){const i=await(await R(n,E.GENERATE_CONTENT,e,!1,JSON.stringify(t),o)).json();return{response:b(i)}}/**
108
- * @license
109
- * Copyright 2024 Google LLC
110
- *
111
- * Licensed under the Apache License, Version 2.0 (the "License");
112
- * you may not use this file except in compliance with the License.
113
- * You may obtain a copy of the License at
114
- *
115
- * http://www.apache.org/licenses/LICENSE-2.0
116
- *
117
- * Unless required by applicable law or agreed to in writing, software
118
- * distributed under the License is distributed on an "AS IS" BASIS,
119
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
120
- * See the License for the specific language governing permissions and
121
- * limitations under the License.
122
- */function de(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function O(e){let n=[];if(typeof e=="string")n=[{text:e}];else for(const t of e)typeof t=="string"?n.push({text:t}):n.push(t);return st(n)}function st(e){const n={role:"user",parts:[]},t={role:"function",parts:[]};let o=!1,s=!1;for(const i of e)"functionResponse"in i?(t.parts.push(i),s=!0):(n.parts.push(i),o=!0);if(o&&s)throw new g("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!o&&!s)throw new g("No content is provided for sending chat message.");return o?n:t}function it(e,n){var t;let o={model:n?.model,generationConfig:n?.generationConfig,safetySettings:n?.safetySettings,tools:n?.tools,toolConfig:n?.toolConfig,systemInstruction:n?.systemInstruction,cachedContent:(t=n?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const s=e.generateContentRequest!=null;if(e.contents){if(s)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");o.contents=e.contents}else if(s)o=Object.assign(Object.assign({},o),e.generateContentRequest);else{const i=O(e);o.contents=[i]}return{generateContentRequest:o}}function J(e){let n;return e.contents?n=e:n={contents:[O(e)]},e.systemInstruction&&(n.systemInstruction=de(e.systemInstruction)),n}function at(e){return typeof e=="string"||Array.isArray(e)?{content:O(e)}:e}/**
123
- * @license
124
- * Copyright 2024 Google LLC
125
- *
126
- * Licensed under the Apache License, Version 2.0 (the "License");
127
- * you may not use this file except in compliance with the License.
128
- * You may obtain a copy of the License at
129
- *
130
- * http://www.apache.org/licenses/LICENSE-2.0
131
- *
132
- * Unless required by applicable law or agreed to in writing, software
133
- * distributed under the License is distributed on an "AS IS" BASIS,
134
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
135
- * See the License for the specific language governing permissions and
136
- * limitations under the License.
137
- */const z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],rt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function ct(e){let n=!1;for(const t of e){const{role:o,parts:s}=t;if(!n&&o!=="user")throw new g(`First content should be with role 'user', got ${o}`);if(!F.includes(o))throw new g(`Each item should include role field. Got ${o} but valid roles are: ${JSON.stringify(F)}`);if(!Array.isArray(s))throw new g("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new g("Each Content should have at least one part");const i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of s)for(const u of z)u in c&&(i[u]+=1);const a=rt[o];for(const c of z)if(!a.includes(c)&&i[c]>0)throw new g(`Content with role '${o}' can't contain '${c}' part`);n=!0}}function X(e){var n;if(e.candidates===void 0||e.candidates.length===0)return!1;const t=(n=e.candidates[0])===null||n===void 0?void 0:n.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const o of t.parts)if(o===void 0||Object.keys(o).length===0||o.text!==void 0&&o.text==="")return!1;return!0}/**
138
- * @license
139
- * Copyright 2024 Google LLC
140
- *
141
- * Licensed under the Apache License, Version 2.0 (the "License");
142
- * you may not use this file except in compliance with the License.
143
- * You may obtain a copy of the License at
144
- *
145
- * http://www.apache.org/licenses/LICENSE-2.0
146
- *
147
- * Unless required by applicable law or agreed to in writing, software
148
- * distributed under the License is distributed on an "AS IS" BASIS,
149
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
150
- * See the License for the specific language governing permissions and
151
- * limitations under the License.
152
- */const Q="SILENT_ERROR";class lt{constructor(n,t,o,s={}){this.model=t,this.params=o,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=n,o?.history&&(ct(o.history),this._history=o.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t);let d;return this._sendPromise=this._sendPromise.then(()=>ue(this._apiKey,this.model,p,f)).then(l=>{var h;if(X(l.response)){this._history.push(r);const m=Object.assign({parts:[],role:"model"},(h=l.response.candidates)===null||h===void 0?void 0:h[0].content);this._history.push(m)}else{const m=C(l.response);m&&console.warn(`sendMessage() was unsuccessful. ${m}. Inspect response object for details.`)}d=l}).catch(l=>{throw this._sendPromise=Promise.resolve(),l}),await this._sendPromise,d}async sendMessageStream(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t),d=le(this._apiKey,this.model,p,f);return this._sendPromise=this._sendPromise.then(()=>d).catch(l=>{throw new Error(Q)}).then(l=>l.response).then(l=>{if(X(l)){this._history.push(r);const h=Object.assign({},l.candidates[0].content);h.role||(h.role="model"),this._history.push(h)}else{const h=C(l);h&&console.warn(`sendMessageStream() was unsuccessful. ${h}. Inspect response object for details.`)}}).catch(l=>{l.message!==Q&&console.error(l)}),d}}/**
153
- * @license
154
- * Copyright 2024 Google LLC
155
- *
156
- * Licensed under the Apache License, Version 2.0 (the "License");
157
- * you may not use this file except in compliance with the License.
158
- * You may obtain a copy of the License at
159
- *
160
- * http://www.apache.org/licenses/LICENSE-2.0
161
- *
162
- * Unless required by applicable law or agreed to in writing, software
163
- * distributed under the License is distributed on an "AS IS" BASIS,
164
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
165
- * See the License for the specific language governing permissions and
166
- * limitations under the License.
167
- */async function ut(e,n,t,o){return(await R(n,E.COUNT_TOKENS,e,!1,JSON.stringify(t),o)).json()}/**
168
- * @license
169
- * Copyright 2024 Google LLC
170
- *
171
- * Licensed under the Apache License, Version 2.0 (the "License");
172
- * you may not use this file except in compliance with the License.
173
- * You may obtain a copy of the License at
174
- *
175
- * http://www.apache.org/licenses/LICENSE-2.0
176
- *
177
- * Unless required by applicable law or agreed to in writing, software
178
- * distributed under the License is distributed on an "AS IS" BASIS,
179
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
180
- * See the License for the specific language governing permissions and
181
- * limitations under the License.
182
- */async function dt(e,n,t,o){return(await R(n,E.EMBED_CONTENT,e,!1,JSON.stringify(t),o)).json()}async function ft(e,n,t,o){const s=t.requests.map(a=>Object.assign(Object.assign({},a),{model:n}));return(await R(n,E.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),o)).json()}/**
183
- * @license
184
- * Copyright 2024 Google LLC
185
- *
186
- * Licensed under the Apache License, Version 2.0 (the "License");
187
- * you may not use this file except in compliance with the License.
188
- * You may obtain a copy of the License at
189
- *
190
- * http://www.apache.org/licenses/LICENSE-2.0
191
- *
192
- * Unless required by applicable law or agreed to in writing, software
193
- * distributed under the License is distributed on an "AS IS" BASIS,
194
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
195
- * See the License for the specific language governing permissions and
196
- * limitations under the License.
197
- */class Z{constructor(n,t,o={}){this.apiKey=n,this._requestOptions=o,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=de(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return ue(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}async generateContentStream(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return le(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}startChat(n){var t;return new lt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},n),this._requestOptions)}async countTokens(n,t={}){const o=it(n,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),t);return ut(this.apiKey,this.model,o,s)}async embedContent(n,t={}){const o=at(n),s=Object.assign(Object.assign({},this._requestOptions),t);return dt(this.apiKey,this.model,o,s)}async batchEmbedContents(n,t={}){const o=Object.assign(Object.assign({},this._requestOptions),t);return ft(this.apiKey,this.model,n,o)}}/**
198
- * @license
199
- * Copyright 2024 Google LLC
200
- *
201
- * Licensed under the Apache License, Version 2.0 (the "License");
202
- * you may not use this file except in compliance with the License.
203
- * You may obtain a copy of the License at
204
- *
205
- * http://www.apache.org/licenses/LICENSE-2.0
206
- *
207
- * Unless required by applicable law or agreed to in writing, software
208
- * distributed under the License is distributed on an "AS IS" BASIS,
209
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
- * See the License for the specific language governing permissions and
211
- * limitations under the License.
212
- */class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(se(s)){const[i]=Le([s]);i.functionDeclarations&&n.push(...i.functionDeclarations)}else if(ie(s)){const{functionDeclarations:i}=pt(s);if(i)n.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(s)}),t.find(s=>"functionDeclarations"in s)?t.map(s=>{if(n?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...n]};return n=[],i}return s}):[...t,...n.length>0?[{functionDeclarations:n}]:[]]}function pt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function gt(e,n){if(!e.length||!n)return;const{toolChoice:t,allowedFunctionNames:o}=n,s={any:w.ANY,auto:w.AUTO,none:w.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof t=="string"||o)return{functionCallingConfig:{mode:w.ANY,allowedFunctionNames:[...o??[],...t&&typeof t=="string"?[t]:[]]}}}var vt=class extends Ie{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Oe("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(t=>t.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new ee(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,n,t){this.apiKey&&(this.client=new ee(this.apiKey).getGenerativeModelFromCachedContent(e,n,t))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:te(e)?.tools,...n})}invocationParams(e){const n=e?.tools?.length?te(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[r]=o;this.client.systemInstruction=r,s=o.slice(1)}const i=this.invocationParams(n);if(this.streaming){const r={},p=this._streamResponseChunks(e,n,t),f={};for await(const l of p){const h=l.generationInfo?.completion??0;f[h]===void 0?f[h]=l:f[h]=f[h].concat(l)}return{generations:Object.entries(f).sort(([l],[h])=>parseInt(l,10)-parseInt(h,10)).map(([l,h])=>h),llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let c;if("usageMetadata"in a.response){const r=a.response.usageMetadata;c={input_tokens:r.promptTokenCount??0,output_tokens:r.candidatesTokenCount??0,total_tokens:r.totalTokenCount??0}}const u=ke(a.response,{usageMetadata:c});return u.generations?.length>0&&await t?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[l]=o;this.client.systemInstruction=l,s=o.slice(1)}const a={...this.invocationParams(n),contents:s},c=await this.caller.callWithOptions({signal:n?.signal},async()=>{const{stream:l}=await this.client.generateContentStream(a);return l});let u,r=0,p=0,f=0,d=0;for await(const l of c){if("usageMetadata"in l&&l.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const m=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,m-r),r=m;const M=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,M-p),p=M;const x=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,x-f),f=x}const h=Ue(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await t?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e)}catch(t){throw t.message?.includes("400 Bad Request")&&(t.status=400),t}})}withStructuredOutput(e,n){const t=e,o=n?.name,s=n?.method,i=n?.includeRaw;if(s==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,c;if(s==="functionCalling"){let f=o??"extract",d;if(ne(t)){const l=N(t);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new U({returnSingle:!0,keyName:f,zodSchema:t})}else{let l;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?(l=t,l.parameters=_(t.parameters),f=t.name):l={name:f,description:t.description??"",parameters:_(t)},d=[{functionDeclarations:[l]}],c=new U({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=N(t);a=this.withConfig({responseSchema:f}),c=new Re}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=D.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=D.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return Se.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{vt as ChatGoogleGenerativeAI};