@mcp-use/inspector 0.9.0 → 0.9.1-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{browser-BwGIHdu_.js → browser-4ZNY5aN0.js} +3 -3
- package/dist/client/assets/{display-A5IEINAP-a27o7vy2.js → display-A5IEINAP-QoSkA9AT.js} +2 -2
- package/dist/client/assets/{embeddings-CiSBpYxK.js → embeddings-D_L9rmdv.js} +1 -1
- package/dist/client/assets/{index-CxUUmVDP.js → index-BMq4azTn.js} +1 -1
- package/dist/client/assets/{index-Dy6u0jar.js → index-COsvUNjY.js} +1 -1
- package/dist/client/assets/{index-BhqX5HqA.js → index-CrgFDb1M.js} +5 -5
- package/dist/client/assets/{index-BkqaguWr.js → index-D6norRlQ.js} +1 -1
- package/dist/client/assets/{index-d3Zt9XHn.js → index-DLaKduRO.js} +1 -1
- package/dist/client/assets/{index-B7PZGsrC.js → index-DzUCqgku.js} +1 -1
- package/dist/client/assets/{index-BlcOpmOB.js → index-TroVhhtI.js} +1 -1
- package/dist/client/assets/{index-BcGM93mv.js → index-wjbb7_xS.js} +1 -1
- package/dist/client/assets/{winston-xjUcWGo7.js → winston-CSWvBloG.js} +1 -1
- package/dist/client/index.html +2 -2
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-
|
|
2
|
-
var Ll=Object.defineProperty;var Dl=(t,e,n)=>e in t?Ll(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var hi=(t,e,n)=>Dl(t,typeof e!="symbol"?e+"":e,n);import{_ as O,bu as ve,bv as Ul,bw as Fl,p as eo,bx as g,a as dn,bg as Rn,by as Xe,bz as Vl,bA as Or,bB as As,bC as Ps,bD as Bl,bE as Hl,bF as Wl,bG as zl}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-QoSkA9AT.js","assets/index-CrgFDb1M.js","assets/index-CHNXgq6o.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Ll=Object.defineProperty;var Dl=(t,e,n)=>e in t?Ll(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var hi=(t,e,n)=>Dl(t,typeof e!="symbol"?e+"":e,n);import{_ as O,bu as ve,bv as Ul,bw as Fl,p as eo,bx as g,a as dn,bg as Rn,by as Xe,bz as Vl,bA as Or,bB as As,bC as Ps,bD as Bl,bE as Hl,bF as Wl,bG as zl}from"./index-CrgFDb1M.js";import{bH as wg,bI as _g,bJ as bg,bK as vg,bL as Sg,bM as Cg,bN as Tg,bO as kg}from"./index-CrgFDb1M.js";import{L as to,S as vs,t as Gl,o as Kl,l as Jl,a as no,T as ql,D as Yl,b as so}from"./index-TroVhhtI.js";import{o as Qs}from"./__vite-browser-external-DFygW7-s.js";import{j as es,d as di,i as Xl}from"./path-C9FudP8b.js";import{af as Zl,ag as Ir,ah as Ql,W as Tn,ai as xe,g as nn,aj as ec,ak as fn,al as fe,H as st,am as ro,j as tc,an as er,_ as q,ao as Xt,a0 as oe,J as N,ap as ee,e as nc,C as sc,aq as rc,ar as ic,V as io,B as oc,as as ac,p as fi,at as lc,au as oo,av as cc,aw as _e,ax as pn,ay as an,M as ao,az as uc,I as Oe,aA as Rr,K as tr,L as Vt,a7 as Bt,aB as hc,aC as dc,aD as fc,aE as pc,aF as mc,aG as gc,aH as yc,aI as wc,aJ as _c,aK as bc,aL as vc,aM as Sc,aN as Cc,aO as Tc,aP as kc,aQ as Ec,aR as xc,aS as Mc,aT as Ac,aU as Pc,aV as Nc,aW as Oc,aX as Ic,aY as Rc,aZ as $c,a_ as jc,a$ as Lc,b0 as Dc,b1 as Uc,X as Fc,b2 as Vc,b3 as Bc,b4 as Hc,D as Le,z as ln,m as $e,Z as Wc,$ as Ze,b5 as Ht,b6 as zc,N as Gc,b7 as pi,b8 as Kc,b9 as mi,ba as gi,bb as $r,bc as yi,a6 as nr,bd as Jc,a3 as qc,be as jr,bf as Ke,bg as ts,u as H,bh as le,bi as Yc,bj as Ae,bk as vt,bl as Xc,bm as Lr,o as U,bn as Zc,i as Qc,T as eu,bo as ns,bp as Fe,bq as F,br as lo,w as ne,bs as tu,bt as $n,bu as nu,bv as co,bw as Wt,bx as mn,by as ss,bz as rs,b as su,bA as ru,ab as iu,a9 as ou,a8 as au,bB as lu}from"./index-D6norRlQ.js";import{E as uo,c as cu,e as uu}from"./embeddings-D_L9rmdv.js";import"./index-DRz5BQNA.js";var Ns,Mn,Os=0,Is=0;function hu(t,e,n){var s=0,r=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Ns),o==null&&(o=Mn)),i==null||o==null){var a=t.random||(t.rng||Zl)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Ns&&!t._v6&&(i[0]|=1,Ns=i)),o==null&&(o=(a[6]<<8|a[7])&16383,Mn===void 0&&!t._v6&&(Mn=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:Is+1,u=l-Os+(c-Is)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Os)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Os=l,Is=c,Mn=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;r[s++]=h>>>24&255,r[s++]=h>>>16&255,r[s++]=h>>>8&255,r[s++]=h&255;var d=l/4294967296*1e4&268435455;r[s++]=d>>>8&255,r[s++]=d&255,r[s++]=d>>>24&15|16,r[s++]=d>>>16&255,r[s++]=o>>>8|128,r[s++]=o&255;for(var f=0;f<6;++f)r[s+f]=i[f];return e||Ir(r)}function du(t){var e=typeof t=="string"?Ql(t):t,n=fu(e);return typeof t=="string"?Ir(n):n}function fu(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function wi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),n.push.apply(n,s)}return n}function _i(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?wi(Object(n),!0).forEach(function(s){pu(t,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):wi(Object(n)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(n,s))})}return t}function pu(t,e,n){return(e=mu(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function mu(t){var e=gu(t,"string");return typeof e=="symbol"?e:e+""}function gu(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var s=n.call(t,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function yu(t={},e,n=0){var s=hu(_i(_i({},t),{},{_v6:!0}),new Uint8Array(16));return s=du(s),Ir(s)}async function*wu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}O(wu,"streamEventsToAISDK");function _u(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}O(_u,"createReadableStreamFromGenerator");async function*bu(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
|
|
3
3
|
🔧 Using tool: ${e.name}
|
|
4
4
|
`;break;case"on_tool_end":yield`
|
|
5
5
|
✅ Tool completed: ${e.name}
|
|
@@ -372,7 +372,7 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
372
372
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
373
373
|
change when you connect to a server):
|
|
374
374
|
{tool_descriptions}
|
|
375
|
-
`,Ft,mg=(Ft=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Qm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new gt,this.telemetry=Nr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zi({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Gm(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Nr.getInstance(),this.llm){const[n,s]=Nl(this.llm);this.modelProvider=n,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Zi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:O(()=>this.getMetadata(),"metadataProvider"),tagsProvider:O(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:O(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:O(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:O(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}g.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&g.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const s=this.serverManager.tools;this._tools=s,this._tools.push(...this.additionalTools),g.info(`🔧 Server manager mode active with ${s.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),g.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(r=>r!=="code_mode").length===0&&(g.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),g.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const r=this.sessions.code_mode;if(r)this._tools=await this.adapter.createToolsFromConnectors([r.connector]),g.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await gt.createTools(this.client),g.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const s of this.connectors)s.isClientConnected||await s.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}g.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),g.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),g.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??eg;this.systemMessage=Rl(e,n,tg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(s=>!(s instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const s=[xl({runLimit:this.maxSteps})],r=gl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:s});return g.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),r}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),g.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&g.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},g.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],g.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[s,r]of Object.entries(e)){if(typeof s!="string"||s.length===0){g.warn(`Invalid metadata key: ${s}. Skipping.`);continue}const i=s.replace(/[^\w-]/g,"_");if(r==null)n[i]=r;else if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")n[i]=r;else if(Array.isArray(r)){const o=r.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof r=="object")try{const o=JSON.stringify(r);o.length>1e3?(g.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=r}catch(o){g.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${i}': ${typeof r}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const s={};for(const r of n)try{const i=this.client.getServerConfig(r);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),s[r]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){g.warn(`Failed to get config for server '${r}': ${i}`),s[r]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=s}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){g.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const s of e)if(typeof s=="object"&&s!==null)"text"in s&&typeof s.text=="string"?n.push(s.text):"content"in s?n.push(this._normalizeOutput(s.content)):n.push(String(s));else{const r=s&&typeof s=="object"&&"text"in s?s.text:null;if(typeof r=="string")n.push(r);else{const i=s&&typeof s=="object"&&"content"in s?s.content:s;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const s=n.getType();if(s==="ai"||s==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const s=n._getType();if(s==="ai"||s==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const s=n.getType();if(s==="human"||s==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:s}=await e.next();if(n)return s}}async run(e,n,s,r,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,s,r,i);const o=this.stream(e,n,s,r,i);return this._consumeAndReturn(o)}async*stream(e,n,s=!0,r,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,s,r,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(s&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const C=this.serverManager.tools,m=new Set(C.map(b=>b.name)),w=new Set(this._tools.map(b=>b.name));(m.size!==w.size||[...m].some(b=>!w.has(b)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=C,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=r??this.conversationHistory,d=[];for(const C of h)(this._isHumanMessageLike(C)||this._isAIMessageLike(C))&&d.push(C);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");g.info(`💬 Received query: '${f}'`),g.info("🏁 Starting agent execution");const y=3;let p=0;const S=[...d,new oe(e)];for(;p<=y;){const C={messages:S};let m=!1;const w=await this._agentExecutor.stream(C,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const b of w){for(const[T,x]of Object.entries(b))if(g.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let _=x.messages;Array.isArray(_)||(_=[_]);for(const v of _)S.includes(v)||S.push(v);for(const v of _){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const M of v.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let R=JSON.stringify(P);R.length>100&&(R=`${R.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${R}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const M=v.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),g.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,R=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(R.size!==V.size||[...R].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...R].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,g.info(`🔃 Restarting execution with updated tools (restart ${p}/${y})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),g.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>y){g.warn(`⚠️ Max restarts (${y}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new oe(e)),c&&this.addToHistory(new N(c))),i&&c)try{g.info("🔧 Attempting structured output...");const C=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(C)}`)),g.info("✅ Structured output successful"),l=!0,C}catch(C){throw g.error(`❌ Structured output failed: ${C}`),new Error(`Failed to generate structured output: ${C instanceof Error?C.message:String(C)}`)}return g.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw g.error(`❌ Error running query: ${h}`),o&&s&&(g.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,y=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:y.length,toolsAvailableNames:y.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:s,externalHistoryUsed:r!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),s&&!this.client&&o&&(g.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(g.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}g.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)g.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)g.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,s=!0,r,i){const{prettyStreamEvents:o}=await dn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-a27o7vy2.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,s,r,i)))yield;return a}async*streamEvents(e,n,s=!0,r,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{s&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);g.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(g.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new oe({content:e})));const y=r??this.conversationHistory,p=[];for(const m of y)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):g.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const S=[...p,new oe(e)];g.info("callbacks",this.callbacks);const C=d.streamEvents({messages:S},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of C)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const b=this._normalizeOutput(w.content);h+=b,g.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,b=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,b=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(b)throw b;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(w)}`)),g.info("✅ Structured output successful"))}catch(m){g.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new N(h));console.log(`
|
|
375
|
+
`,Ft,mg=(Ft=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Qm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new gt,this.telemetry=Nr.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Zi({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new gt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Gm(this.client,this.adapter)}else this.adapter=e.adapter??new gt(this.disallowedTools);if(this.telemetry=Nr.getInstance(),this.llm){const[n,s]=Nl(this.llm);this.modelProvider=n,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Zi({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:O(()=>this.getMetadata(),"metadataProvider"),tagsProvider:O(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:O(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:O(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:O(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}g.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&g.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const s=this.serverManager.tools;this._tools=s,this._tools.push(...this.additionalTools),g.info(`🔧 Server manager mode active with ${s.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),g.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(r=>r!=="code_mode").length===0&&(g.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),g.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const r=this.sessions.code_mode;if(r)this._tools=await this.adapter.createToolsFromConnectors([r.connector]),g.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await gt.createTools(this.client),g.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{g.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const s of this.connectors)s.isClientConnected||await s.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),g.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}g.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),g.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),g.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??eg;this.systemMessage=Rl(e,n,tg,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(s=>!(s instanceof _e))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);g.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const s=[xl({runLimit:this.maxSteps})],r=gl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:s});return g.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),r}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new _e(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof _e)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),g.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new gt(this.disallowedTools),this._initialized&&g.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},g.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],g.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[s,r]of Object.entries(e)){if(typeof s!="string"||s.length===0){g.warn(`Invalid metadata key: ${s}. Skipping.`);continue}const i=s.replace(/[^\w-]/g,"_");if(r==null)n[i]=r;else if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")n[i]=r;else if(Array.isArray(r)){const o=r.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof r=="object")try{const o=JSON.stringify(r);o.length>1e3?(g.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=r}catch(o){g.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else g.warn(`Unsupported metadata value type for key '${i}': ${typeof r}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const s={};for(const r of n)try{const i=this.client.getServerConfig(r);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),s[r]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){g.warn(`Failed to get config for server '${r}': ${i}`),s[r]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=s}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){g.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const s of e)if(typeof s=="object"&&s!==null)"text"in s&&typeof s.text=="string"?n.push(s.text):"content"in s?n.push(this._normalizeOutput(s.content)):n.push(String(s));else{const r=s&&typeof s=="object"&&"text"in s?s.text:null;if(typeof r=="string")n.push(r);else{const i=s&&typeof s=="object"&&"content"in s?s.content:s;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof N)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const s=n.getType();if(s==="ai"||s==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const s=n._getType();if(s==="ai"||s==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof oe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const s=n.getType();if(s==="human"||s==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof U)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof N||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:s}=await e.next();if(n)return s}}async run(e,n,s,r,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,s,r,i);const o=this.stream(e,n,s,r,i);return this._consumeAndReturn(o)}async*stream(e,n,s=!0,r,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,s,r,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(s&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const C=this.serverManager.tools,m=new Set(C.map(b=>b.name)),w=new Set(this._tools.map(b=>b.name));(m.size!==w.size||[...m].some(b=>!w.has(b)))&&(g.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=C,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=r??this.conversationHistory,d=[];for(const C of h)(this._isHumanMessageLike(C)||this._isAIMessageLike(C))&&d.push(C);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");g.info(`💬 Received query: '${f}'`),g.info("🏁 Starting agent execution");const y=3;let p=0;const S=[...d,new oe(e)];for(;p<=y;){const C={messages:S};let m=!1;const w=await this._agentExecutor.stream(C,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const b of w){for(const[T,x]of Object.entries(b))if(g.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let _=x.messages;Array.isArray(_)||(_=[_]);for(const v of _)S.includes(v)||S.push(v);for(const v of _){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const M of v.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let R=JSON.stringify(P);R.length>100&&(R=`${R.slice(0,97)}...`),g.info(`🔧 Tool call: ${E} with input: ${R}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const M=v.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),g.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,R=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(R.size!==V.size||[...R].some(X=>!V.has(X))){g.info(`🔄 Tools changed during execution. New tools: ${[...R].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,g.info(`🔃 Restarting execution with updated tools (restart ${p}/${y})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),g.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>y){g.warn(`⚠️ Max restarts (${y}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new oe(e)),c&&this.addToHistory(new N(c))),i&&c)try{g.info("🔧 Attempting structured output...");const C=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(C)}`)),g.info("✅ Structured output successful"),l=!0,C}catch(C){throw g.error(`❌ Structured output failed: ${C}`),new Error(`Failed to generate structured output: ${C instanceof Error?C.message:String(C)}`)}return g.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw g.error(`❌ Error running query: ${h}`),o&&s&&(g.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,y=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:y.length,toolsAvailableNames:y.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:s,externalHistoryUsed:r!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),s&&!this.client&&o&&(g.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(g.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}g.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)g.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)g.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new gt)}finally{this._initialized=!1,g.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,s=!0,r,i){const{prettyStreamEvents:o}=await dn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-QoSkA9AT.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,s,r,i)))yield;return a}async*streamEvents(e,n,s=!0,r,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{s&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);g.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(g.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new oe({content:e})));const y=r??this.conversationHistory,p=[];for(const m of y)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):g.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const S=[...p,new oe(e)];g.info("callbacks",this.callbacks);const C=d.streamEvents({messages:S},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of C)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const b=this._normalizeOutput(w.content);h+=b,g.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){g.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,b=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,b=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(b)throw b;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new N(`Structured result: ${JSON.stringify(w)}`)),g.info("✅ Structured output successful"))}catch(m){g.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new N(h));console.log(`
|
|
376
376
|
|
|
377
377
|
`),g.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw g.error(`❌ Error during streamEvents: ${d}`),o&&s&&(g.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),d}finally{const d=Date.now()-a;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const y=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:s,externalHistoryUsed:r!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:d,errorType:l?null:"streaming_error",conversationHistoryLength:y}),s&&!this.client&&o&&(g.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,s){g.info(`🔄 Attempting structured output with schema: ${JSON.stringify(s,null,2)}`),g.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let r=null,i="";if(g.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Rn(s),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")r=n.withStructuredOutput(s);else if(n)r=n;else throw new Error("LLM is required for structured output");const o=Rn(s),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),g.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),g.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){g.info(`🔄 Structured output attempt ${f}/${h}`);let y=`
|
|
378
378
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{_ as a,a as k}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-wjbb7_xS.js","assets/index-CrgFDb1M.js","assets/index-CHNXgq6o.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a,a as k}from"./index-CrgFDb1M.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-wjbb7_xS.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
|
|
3
3
|
✨ For enhanced console output with colors and syntax highlighting, install:
|
|
4
4
|
|
|
5
5
|
npm install chalk cli-highlight
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as c,A as d}from"./index-
|
|
1
|
+
import{_ as c,A as d}from"./index-D6norRlQ.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{M as Ss,t as xa,a1 as ka,a2 as S,a3 as Sa,a4 as Aa,W as Ca,X as jn,j as Ke,P as As,a5 as Ln,Y as Dn,H as Ze,a6 as Oa,a7 as Ia,Z as Fn,$ as Ta,Q as Cs,S as Os,J as ke,o as Is,a8 as $a,L as cn,a9 as Bn,aa as Ra,ab as Pa,ac as Ea,U as Un,ad as Wn,ae as Ma,K as Jt,a as Na}from"./index-
|
|
1
|
+
import{M as Ss,t as xa,a1 as ka,a2 as S,a3 as Sa,a4 as Aa,W as Ca,X as jn,j as Ke,P as As,a5 as Ln,Y as Dn,H as Ze,a6 as Oa,a7 as Ia,Z as Fn,$ as Ta,Q as Cs,S as Os,J as ke,o as Is,a8 as $a,L as cn,a9 as Bn,aa as Ra,ab as Pa,ac as Ea,U as Un,ad as Wn,ae as Ma,K as Jt,a as Na}from"./index-D6norRlQ.js";import{bg as Ts,bh as ja}from"./index-CrgFDb1M.js";import{J as qn,c as La,p as $s,m as Kt}from"./index-TroVhhtI.js";import"./embeddings-D_L9rmdv.js";import"./index-DRz5BQNA.js";const xe=t=>t();function Be(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function Da(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function Ue(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!Ss.isInstance(t))throw new Error("Invalid generic chat message");return Da(t);default:throw new Error(`Unknown message type: ${e}`)}}function Fa(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:s,azureOpenAIBasePath:r,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=t;if((s||i)&&r&&e)return`${r}/${e}`;if((s||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(s||i){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return a}function Ba(t,e){let n;return xa(t)?n=ka(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function Ua(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function Wa(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(Rs(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
2
2
|
`)}function Rs(t,e){const n=[];for(const[s,r]of Object.entries(t.properties??{}))r.description&&e<2&&n.push(`// ${r.description}`),t.required?.includes(s)?n.push(`${s}: ${ut(r,e)},`):n.push(`${s}?: ${ut(r,e)},`);return n.map(s=>" ".repeat(e)+s).join(`
|
|
3
3
|
`)}function ut(t,e){if(Ua(t))return t.anyOf.map(n=>ut(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",Rs(t,e+2),"}"].join(`
|
|
4
4
|
`);case"array":return t.items?`${ut(t.items,e)}[]`:"any[]";default:return""}}function Ps(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function un(t){return"type"in t&&t.type!=="function"}function qa(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function dt(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function Es(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function Ja(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function Ka(t){return t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function Za(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function za(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}function Zt(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const zt=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class x extends Error{}class q extends x{constructor(e,n,s,r){super(`${q.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new kt({message:s,cause:zt(n)});const a=n?.error;return e===400?new Ms(e,a,s,r):e===401?new Ns(e,a,s,r):e===403?new js(e,a,s,r):e===404?new Ls(e,a,s,r):e===409?new Ds(e,a,s,r):e===422?new Fs(e,a,s,r):e===429?new Bs(e,a,s,r):e>=500?new Us(e,a,s,r):new q(e,a,s,r)}}class X extends q{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class kt extends q{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class St extends kt{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ms extends q{}class Ns extends q{}class js extends q{}class Ls extends q{}class Ds extends q{}class Fs extends q{}class Bs extends q{}class Us extends q{}class Ws extends x{constructor(){super("Could not parse response content as the length limit was reached")}}class qs extends x{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Oe extends Error{constructor(e){super(e)}}function ht(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ha(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function dn(t){return t?.$brand==="auto-parseable-response-format"}function We(t){return t?.$brand==="auto-parseable-tool"}function Va(t,e){return!e||!Js(e)?{...t,choices:t.choices.map(n=>(Ks(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:hn(t,e)}function hn(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new Ws;if(s.finish_reason==="content_filter")throw new qs;return Ks(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>Ga(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Xa(e,s.message.content):null}}});return{...t,choices:n}}function Xa(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function Ga(t,e){const n=t.tools?.find(s=>ht(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:We(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function Qa(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>ht(s)&&s.function?.name===e.function.name);return ht(n)&&(We(n)||n?.function.strict||!1)}function Js(t){return dn(t.response_format)?!0:t.tools?.some(e=>We(e)||e.type==="function"&&e.function.strict===!0)??!1}function Ks(t){for(const e of t||[])if(e.type!=="function")throw new x(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Ya(t){for(const e of t??[]){if(e.type!=="function")throw new x(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new x(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const ei=Symbol("Let zodToJsonSchema decide on which parser to use"),Jn={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},ti=t=>typeof t=="string"?{...Jn,basePath:["#"],definitions:{},name:t}:{...Jn,basePath:["#"],definitions:{},...t},Ht=t=>"_def"in t?t._def:t;function ni(t){if(!t)return!0;for(const e in t)return!1;return!0}const si=t=>{const e=ti(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([s,r])=>[Ht(r),{def:Ht(r),path:[...e.basePath,e.definitionPath,s],jsonSchema:void 0}]))}};function Zs(t,e,n,s){s?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function T(t,e,n,s,r){t[e]=n,Zs(t,e,s,r)}function ri(){return{}}function ai(t,e){const n={type:"array"};return t.type?._def?.typeName!==S.ZodAny&&(n.items=O(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&T(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&T(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(T(n,"minItems",t.exactLength.value,t.exactLength.message,e),T(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function ii(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const s of t.checks)switch(s.kind){case"min":e.target==="jsonSchema7"?s.inclusive?T(n,"minimum",s.value,s.message,e):T(n,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(n.exclusiveMinimum=!0),T(n,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?T(n,"maximum",s.value,s.message,e):T(n,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(n.exclusiveMaximum=!0),T(n,"maximum",s.value,s.message,e));break;case"multipleOf":T(n,"multipleOf",s.value,s.message,e);break}return n}function oi(){return{type:"boolean"}}function li(t,e){return O(t.type._def,e)}const ci=(t,e)=>O(t.innerType._def,e);function zs(t,e,n){const s=n??e.dateStrategy;if(Array.isArray(s))return{anyOf:s.map((r,a)=>zs(t,e,r))};switch(s){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ui(t,e)}}const ui=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const s of t.checks)switch(s.kind){case"min":T(n,"minimum",s.value,s.message,e);break;case"max":T(n,"maximum",s.value,s.message,e);break}return n};function di(t,e){return{...O(t.innerType._def,e),default:t.defaultValue()}}function hi(t,e,n){return e.effectStrategy==="input"?O(t.schema._def,e,n):{}}function fi(t){return{type:"string",enum:[...t.values]}}const pi=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function mi(t,e){const n=[O(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),O(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let s=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const r=[];return n.forEach(a=>{if(pi(a))r.push(...a.allOf),a.unevaluatedProperties===void 0&&(s=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...c}=a;i=c}else s=void 0;r.push(i)}}),r.length?{allOf:r,...s}:void 0}function _i(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Nt;const le={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Nt===void 0&&(Nt=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Nt),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Hs(t,e){const n={type:"string"};function s(r){return e.patternStrategy==="escape"?gi(r):r}if(t.checks)for(const r of t.checks)switch(r.kind){case"min":T(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":T(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":G(n,"email",r.message,e);break;case"format:idn-email":G(n,"idn-email",r.message,e);break;case"pattern:zod":Q(n,le.email,r.message,e);break}break;case"url":G(n,"uri",r.message,e);break;case"uuid":G(n,"uuid",r.message,e);break;case"regex":Q(n,r.regex,r.message,e);break;case"cuid":Q(n,le.cuid,r.message,e);break;case"cuid2":Q(n,le.cuid2,r.message,e);break;case"startsWith":Q(n,RegExp(`^${s(r.value)}`),r.message,e);break;case"endsWith":Q(n,RegExp(`${s(r.value)}$`),r.message,e);break;case"datetime":G(n,"date-time",r.message,e);break;case"date":G(n,"date",r.message,e);break;case"time":G(n,"time",r.message,e);break;case"duration":G(n,"duration",r.message,e);break;case"length":T(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),T(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Q(n,RegExp(s(r.value)),r.message,e);break}case"ip":{r.version!=="v6"&&G(n,"ipv4",r.message,e),r.version!=="v4"&&G(n,"ipv6",r.message,e);break}case"emoji":Q(n,le.emoji,r.message,e);break;case"ulid":{Q(n,le.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{G(n,"binary",r.message,e);break}case"contentEncoding:base64":{T(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Q(n,le.base64,r.message,e);break}}break}case"nanoid":Q(n,le.nanoid,r.message,e)}return n}const gi=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),G=(t,e,n,s)=>{t.format||t.anyOf?.some(r=>r.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&s.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&s.errorMessages&&{errorMessage:{format:n}}})):T(t,"format",e,n,s)},Q=(t,e,n,s)=>{t.pattern||t.allOf?.some(r=>r.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&s.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Kn(e,s),...n&&s.errorMessages&&{errorMessage:{pattern:n}}})):T(t,"pattern",Kn(e,s),n,s)},Kn=(t,e)=>{const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const s={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=s.i?n.source.toLowerCase():n.source;let a="",i=!1,o=!1,c=!1;for(let l=0;l<r.length;l++){if(i){a+=r[l],i=!1;continue}if(s.i){if(o){if(r[l].match(/[a-z]/)){c?(a+=r[l],a+=`${r[l-2]}-${r[l]}`.toUpperCase(),c=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(a+=r[l],c=!0):a+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){a+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(s.m){if(r[l]==="^"){a+=`(^|(?<=[\r
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{j as ie,H as ge,I as me,J as ye,K as Ce,L as _e,M as Ee,N as ve,a as ae,t as re,P as ce,Q as we,S as Te,U as N,V as Ie,i as Oe,O as Re,W as Se,X as Ae,Y as Ne,Z as U,$ as be}from"./index-BkqaguWr.js";import"./embeddings-CiSBpYxK.js";import"./index-BhqX5HqA.js";import"./index-DRz5BQNA.js";function E(e){if(typeof e=="object"&&e!==null){const t={...e};"additionalProperties"in t&&delete t.additionalProperties,"$schema"in t&&delete t.$schema,"strict"in t&&delete t.strict;for(const n in t)n in t&&(Array.isArray(t[n])?t[n]=t[n].map(E):typeof t[n]=="object"&&t[n]!==null&&(t[n]=E(t[n])));return t}return e}function x(e){const t=E(ie(e)?ge(e):e),{$schema:n,...o}=t;return o}function xe(e){const t=E(e),{$schema:n,...o}=t;return o}const g=[];for(let e=0;e<256;++e)g.push((e+256).toString(16).slice(1));function Me(e,t=0){return(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase()}let b;const De=new Uint8Array(16);function Ge(){if(!b){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");b=crypto.getRandomValues.bind(crypto)}return b(De)}const Ue=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),k={randomUUID:Ue};function le(e,t,n){if(k.randomUUID&&!e)return k.randomUUID();e=e||{};const o=e.random??e.rng?.()??Ge();if(o.length<16)throw new Error("Random bytes length must be >= 16");return o[6]=o[6]&15|64,o[8]=o[8]&63|128,Me(o)}function ke(e){const t=e._getType();return Ee.isInstance(e)?e.role:t==="tool"?t:e.name??t}function Le(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 Pe(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 je(e,t){return t.map(n=>ae(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===e.tool_call_id)?.name}function Fe(e){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!e)throw new Error("This model does not support images");if(n.source_type==="url"){const o=N({dataUrl:n.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardAudioBlock(n){if(!e)throw new Error("This model does not support audio");if(n.source_type==="url"){const o=N({dataUrl:n.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardFileBlock(n){if(!e)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const o=N({dataUrl:n.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)}}}function L(e,t){if(we(e))return Te(e,Fe(t));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(!t)throw new Error("This model does not support images");let n;if(typeof e.image_url=="string")n=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)n=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=n.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 Pe(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 Ke(e,t,n){if(ve(e)){const i=e.name??je(e,n);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=>L(c,t)).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=>L(i,t)).filter(i=>i!==void 0)),ae(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function P(e,t,n=!1){return e.reduce((o,s,i)=>{if(!me(s))throw new Error("Unsupported message input");const a=ke(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=Le(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=Ke(s,t,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"&&!n)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!n,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function $e(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const n=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 ye({content:a??"",tool_calls:n?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:le()})),additional_kwargs:{...i},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function He(e,t){if(!e.candidates||e.candidates.length===0)return null;const n=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 n&&u.push(...n.map(r=>({...r,args:JSON.stringify(r.args),index:t.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:le()}))),new Ce({text:c,message:new _e({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:t.usageMetadata}),generationInfo:i})}function Be(e){return e.every(t=>"functionDeclarations"in t&&Array.isArray(t.functionDeclarations))?e:[{functionDeclarations:e.map(t=>{if(re(t)){const n=x(t.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:t.name,description:t.description}:{name:t.name,description:t.description,parameters:n}}return ce(t)?{name:t.function.name,description:t.function.description??"A function available to call.",parameters:xe(t.function.parameters)}:t})}]}var j=class extends Ie{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 t=await Oe(this.zodSchema,e);if(t.success)return t.data;throw new Re(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const t=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(t[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=t;return await this._validateResult(n.args)}},F;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(F||(F={}));var K;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(K||(K={}));var $;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const H=["user","model","function","system"];var B;(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"})(B||(B={}));var Y;(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"})(Y||(Y={}));var q;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(q||(q={}));var V;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(V||(V={}));var I;(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"})(I||(I={}));var W;(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"})(W||(W={}));var T;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(T||(T={}));var J;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(J||(J={}));class m extends Error{constructor(t){super(`[GoogleGenerativeAI Error]: ${t}`)}}class w extends m{constructor(t,n){super(t),this.response=n}}class ue extends m{constructor(t,n,o,s){super(t),this.status=n,this.statusText=o,this.errorDetails=s}}class _ extends m{}class de extends m{}const Ye="https://generativelanguage.googleapis.com",qe="v1beta",Ve="0.24.1",We="genai-js";var v;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Je{constructor(t,n,o,s,i){this.model=t,this.task=n,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var t,n;const o=((t=this.requestOptions)===null||t===void 0?void 0:t.apiVersion)||qe;let i=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Ye}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function ze(e){const t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${We}/${Ve}`),t.join(" ")}async function Xe(e){var t;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",ze(e.requestOptions)),n.append("x-goog-api-key",e.apiKey);let o=(t=e.requestOptions)===null||t===void 0?void 0:t.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new _(`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 _(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new _(`Header name ${s} can only be set using the apiClient field`);n.append(s,i)}}return n}async function Qe(e,t,n,o,s,i){const a=new Je(e,t,n,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},nt(i)),{method:"POST",headers:await Xe(a),body:s})}}async function S(e,t,n,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Qe(e,t,n,o,s,i);return Ze(c,u,a)}async function Ze(e,t,n=fetch){let o;try{o=await n(e,t)}catch(s){et(s,e)}return o.ok||await tt(o,e),o}function et(e,t){let n=e;throw n.name==="AbortError"?(n=new de(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof ue||e instanceof _||(n=new m(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function tt(e,t){let n="",o;try{const s=await e.json();n=s.error.message,s.error.details&&(n+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new ue(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,o)}function nt(e){const t={};if(e?.signal!==void 0||e?.timeout>=0){const n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{n.abort()}),t.signal=n.signal}return t}function M(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.`),A(e.candidates[0]))throw new w(`${C(e)}`,e);return ot(e)}else if(e.promptFeedback)throw new w(`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.`),A(e.candidates[0]))throw new w(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),z(e)[0]}else if(e.promptFeedback)throw new w(`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.`),A(e.candidates[0]))throw new w(`${C(e)}`,e);return z(e)}else if(e.promptFeedback)throw new w(`Function call not available. ${C(e)}`,e)},e}function ot(e){var t,n,o,s;const i=[];if(!((n=(t=e.candidates)===null||t===void 0?void 0:t[0].content)===null||n===void 0)&&n.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+`
|
|
1
|
+
import{j as ie,H as ge,I as me,J as ye,K as Ce,L as _e,M as Ee,N as ve,a as ae,t as re,P as ce,Q as we,S as Te,U as N,V as Ie,i as Oe,O as Re,W as Se,X as Ae,Y as Ne,Z as U,$ as be}from"./index-D6norRlQ.js";import"./embeddings-D_L9rmdv.js";import"./index-CrgFDb1M.js";import"./index-DRz5BQNA.js";function E(e){if(typeof e=="object"&&e!==null){const t={...e};"additionalProperties"in t&&delete t.additionalProperties,"$schema"in t&&delete t.$schema,"strict"in t&&delete t.strict;for(const n in t)n in t&&(Array.isArray(t[n])?t[n]=t[n].map(E):typeof t[n]=="object"&&t[n]!==null&&(t[n]=E(t[n])));return t}return e}function x(e){const t=E(ie(e)?ge(e):e),{$schema:n,...o}=t;return o}function xe(e){const t=E(e),{$schema:n,...o}=t;return o}const g=[];for(let e=0;e<256;++e)g.push((e+256).toString(16).slice(1));function Me(e,t=0){return(g[e[t+0]]+g[e[t+1]]+g[e[t+2]]+g[e[t+3]]+"-"+g[e[t+4]]+g[e[t+5]]+"-"+g[e[t+6]]+g[e[t+7]]+"-"+g[e[t+8]]+g[e[t+9]]+"-"+g[e[t+10]]+g[e[t+11]]+g[e[t+12]]+g[e[t+13]]+g[e[t+14]]+g[e[t+15]]).toLowerCase()}let b;const De=new Uint8Array(16);function Ge(){if(!b){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");b=crypto.getRandomValues.bind(crypto)}return b(De)}const Ue=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),k={randomUUID:Ue};function le(e,t,n){if(k.randomUUID&&!e)return k.randomUUID();e=e||{};const o=e.random??e.rng?.()??Ge();if(o.length<16)throw new Error("Random bytes length must be >= 16");return o[6]=o[6]&15|64,o[8]=o[8]&63|128,Me(o)}function ke(e){const t=e._getType();return Ee.isInstance(e)?e.role:t==="tool"?t:e.name??t}function Le(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 Pe(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 je(e,t){return t.map(n=>ae(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===e.tool_call_id)?.name}function Fe(e){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!e)throw new Error("This model does not support images");if(n.source_type==="url"){const o=N({dataUrl:n.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardAudioBlock(n){if(!e)throw new Error("This model does not support audio");if(n.source_type==="url"){const o=N({dataUrl:n.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)},fromStandardFileBlock(n){if(!e)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const o=N({dataUrl:n.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:n.mime_type??"",fileUri:n.url}}}if(n.source_type==="base64")return{inlineData:{mimeType:n.mime_type??"",data:n.data}};throw new Error(`Unsupported source type: ${n.source_type}`)}}}function L(e,t){if(we(e))return Te(e,Fe(t));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(!t)throw new Error("This model does not support images");let n;if(typeof e.image_url=="string")n=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)n=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=n.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 Pe(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 Ke(e,t,n){if(ve(e)){const i=e.name??je(e,n);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=>L(c,t)).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=>L(i,t)).filter(i=>i!==void 0)),ae(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function P(e,t,n=!1){return e.reduce((o,s,i)=>{if(!me(s))throw new Error("Unsupported message input");const a=ke(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=Le(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=Ke(s,t,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"&&!n)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!n,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function $e(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const n=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 ye({content:a??"",tool_calls:n?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:le()})),additional_kwargs:{...i},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function He(e,t){if(!e.candidates||e.candidates.length===0)return null;const n=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 n&&u.push(...n.map(r=>({...r,args:JSON.stringify(r.args),index:t.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:le()}))),new Ce({text:c,message:new _e({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:t.usageMetadata}),generationInfo:i})}function Be(e){return e.every(t=>"functionDeclarations"in t&&Array.isArray(t.functionDeclarations))?e:[{functionDeclarations:e.map(t=>{if(re(t)){const n=x(t.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:t.name,description:t.description}:{name:t.name,description:t.description,parameters:n}}return ce(t)?{name:t.function.name,description:t.function.description??"A function available to call.",parameters:xe(t.function.parameters)}:t})}]}var j=class extends Ie{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 t=await Oe(this.zodSchema,e);if(t.success)return t.data;throw new Re(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const t=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(t[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=t;return await this._validateResult(n.args)}},F;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(F||(F={}));var K;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(K||(K={}));var $;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const H=["user","model","function","system"];var B;(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"})(B||(B={}));var Y;(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"})(Y||(Y={}));var q;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(q||(q={}));var V;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(V||(V={}));var I;(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"})(I||(I={}));var W;(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"})(W||(W={}));var T;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(T||(T={}));var J;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(J||(J={}));class m extends Error{constructor(t){super(`[GoogleGenerativeAI Error]: ${t}`)}}class w extends m{constructor(t,n){super(t),this.response=n}}class ue extends m{constructor(t,n,o,s){super(t),this.status=n,this.statusText=o,this.errorDetails=s}}class _ extends m{}class de extends m{}const Ye="https://generativelanguage.googleapis.com",qe="v1beta",Ve="0.24.1",We="genai-js";var v;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Je{constructor(t,n,o,s,i){this.model=t,this.task=n,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var t,n;const o=((t=this.requestOptions)===null||t===void 0?void 0:t.apiVersion)||qe;let i=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Ye}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function ze(e){const t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${We}/${Ve}`),t.join(" ")}async function Xe(e){var t;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",ze(e.requestOptions)),n.append("x-goog-api-key",e.apiKey);let o=(t=e.requestOptions)===null||t===void 0?void 0:t.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new _(`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 _(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new _(`Header name ${s} can only be set using the apiClient field`);n.append(s,i)}}return n}async function Qe(e,t,n,o,s,i){const a=new Je(e,t,n,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},nt(i)),{method:"POST",headers:await Xe(a),body:s})}}async function S(e,t,n,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Qe(e,t,n,o,s,i);return Ze(c,u,a)}async function Ze(e,t,n=fetch){let o;try{o=await n(e,t)}catch(s){et(s,e)}return o.ok||await tt(o,e),o}function et(e,t){let n=e;throw n.name==="AbortError"?(n=new de(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof ue||e instanceof _||(n=new m(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function tt(e,t){let n="",o;try{const s=await e.json();n=s.error.message,s.error.details&&(n+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new ue(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,o)}function nt(e){const t={};if(e?.signal!==void 0||e?.timeout>=0){const n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{n.abort()}),t.signal=n.signal}return t}function M(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.`),A(e.candidates[0]))throw new w(`${C(e)}`,e);return ot(e)}else if(e.promptFeedback)throw new w(`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.`),A(e.candidates[0]))throw new w(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),z(e)[0]}else if(e.promptFeedback)throw new w(`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.`),A(e.candidates[0]))throw new w(`${C(e)}`,e);return z(e)}else if(e.promptFeedback)throw new w(`Function call not available. ${C(e)}`,e)},e}function ot(e){var t,n,o,s;const i=[];if(!((n=(t=e.candidates)===null||t===void 0?void 0:t[0].content)===null||n===void 0)&&n.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+`
|
|
2
2
|
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function z(e){var t,n,o,s;const i=[];if(!((n=(t=e.candidates)===null||t===void 0?void 0:t[0].content)===null||n===void 0)&&n.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 st=[I.RECITATION,I.SAFETY,I.LANGUAGE];function A(e){return!!e.finishReason&&st.includes(e.finishReason)}function C(e){var t,n,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((t=e.promptFeedback)===null||t===void 0)&&t.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((n=e.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];A(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function O(e){return this instanceof O?(this.v=e,this):new O(e)}function it(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=n.apply(e,t||[]),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,y){i.push([d,l,h,y])>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 O?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])}}const X=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function at(e){const t=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=lt(t),[o,s]=n.tee();return{stream:ct(o),response:rt(s)}}async function rt(e){const t=[],n=e.getReader();for(;;){const{done:o,value:s}=await n.read();if(o)return M(ut(t));t.push(s)}}function ct(e){return it(this,arguments,function*(){const n=e.getReader();for(;;){const{value:o,done:s}=yield O(n.read());if(s)break;yield yield O(M(o))}})}function lt(e){const t=e.getReader();return new ReadableStream({start(o){let s="";return i();function i(){return t.read().then(({value:a,done:c})=>{if(c){if(s.trim()){o.error(new m("Failed to parse stream"));return}o.close();return}s+=a;let u=s.match(X),r;for(;u;){try{r=JSON.parse(u[1])}catch{o.error(new m(`Error parsing JSON response: "${u[1]}"`));return}o.enqueue(r),s=s.substring(u[0].length),u=s.match(X)}return i()}).catch(a=>{let c=a;throw c.stack=a.stack,c.name==="AbortError"?c=new de("Request aborted when reading from the stream"):c=new m("Error reading from the stream"),c})}}})}function ut(e){const t=e[e.length-1],n={promptFeedback:t?.promptFeedback};for(const o of e){if(o.candidates){let s=0;for(const i of o.candidates)if(n.candidates||(n.candidates=[]),n.candidates[s]||(n.candidates[s]={index:s}),n.candidates[s].citationMetadata=i.citationMetadata,n.candidates[s].groundingMetadata=i.groundingMetadata,n.candidates[s].finishReason=i.finishReason,n.candidates[s].finishMessage=i.finishMessage,n.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){n.candidates[s].content||(n.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=""),n.candidates[s].content.parts.push(a)}s++}o.usageMetadata&&(n.usageMetadata=o.usageMetadata)}return n}async function fe(e,t,n,o){const s=await S(t,v.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),o);return at(s)}async function he(e,t,n,o){const i=await(await S(t,v.GENERATE_CONTENT,e,!1,JSON.stringify(n),o)).json();return{response:M(i)}}function pe(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 R(e){let t=[];if(typeof e=="string")t=[{text:e}];else for(const n of e)typeof n=="string"?t.push({text:n}):t.push(n);return dt(t)}function dt(e){const t={role:"user",parts:[]},n={role:"function",parts:[]};let o=!1,s=!1;for(const i of e)"functionResponse"in i?(n.parts.push(i),s=!0):(t.parts.push(i),o=!0);if(o&&s)throw new m("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 m("No content is provided for sending chat message.");return o?t:n}function ft(e,t){var n;let o={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:(n=t?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const s=e.generateContentRequest!=null;if(e.contents){if(s)throw new _("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=R(e);o.contents=[i]}return{generateContentRequest:o}}function Q(e){let t;return e.contents?t=e:t={contents:[R(e)]},e.systemInstruction&&(t.systemInstruction=pe(e.systemInstruction)),t}function ht(e){return typeof e=="string"||Array.isArray(e)?{content:R(e)}:e}const Z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],pt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function gt(e){let t=!1;for(const n of e){const{role:o,parts:s}=n;if(!t&&o!=="user")throw new m(`First content should be with role 'user', got ${o}`);if(!H.includes(o))throw new m(`Each item should include role field. Got ${o} but valid roles are: ${JSON.stringify(H)}`);if(!Array.isArray(s))throw new m("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new m("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=pt[o];for(const c of Z)if(!a.includes(c)&&i[c]>0)throw new m(`Content with role '${o}' can't contain '${c}' part`);t=!0}}function ee(e){var t;if(e.candidates===void 0||e.candidates.length===0)return!1;const n=(t=e.candidates[0])===null||t===void 0?void 0:t.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const o of n.parts)if(o===void 0||Object.keys(o).length===0||o.text!==void 0&&o.text==="")return!1;return!0}const te="SILENT_ERROR";class mt{constructor(t,n,o,s={}){this.model=n,this.params=o,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=t,o?.history&&(gt(o.history),this._history=o.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(t,n={}){var o,s,i,a,c,u;await this._sendPromise;const r=R(t),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),n);let d;return this._sendPromise=this._sendPromise.then(()=>he(this._apiKey,this.model,p,f)).then(l=>{var h;if(ee(l.response)){this._history.push(r);const y=Object.assign({parts:[],role:"model"},(h=l.response.candidates)===null||h===void 0?void 0:h[0].content);this._history.push(y)}else{const y=C(l.response);y&&console.warn(`sendMessage() was unsuccessful. ${y}. Inspect response object for details.`)}d=l}).catch(l=>{throw this._sendPromise=Promise.resolve(),l}),await this._sendPromise,d}async sendMessageStream(t,n={}){var o,s,i,a,c,u;await this._sendPromise;const r=R(t),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),n),d=fe(this._apiKey,this.model,p,f);return this._sendPromise=this._sendPromise.then(()=>d).catch(l=>{throw new Error(te)}).then(l=>l.response).then(l=>{if(ee(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!==te&&console.error(l)}),d}}async function yt(e,t,n,o){return(await S(t,v.COUNT_TOKENS,e,!1,JSON.stringify(n),o)).json()}async function Ct(e,t,n,o){return(await S(t,v.EMBED_CONTENT,e,!1,JSON.stringify(n),o)).json()}async function _t(e,t,n,o){const s=n.requests.map(a=>Object.assign(Object.assign({},a),{model:t}));return(await S(t,v.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),o)).json()}class ne{constructor(t,n,o={}){this.apiKey=t,this._requestOptions=o,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=pe(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(t,n={}){var o;const s=Q(t),i=Object.assign(Object.assign({},this._requestOptions),n);return he(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(t,n={}){var o;const s=Q(t),i=Object.assign(Object.assign({},this._requestOptions),n);return fe(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(t){var n;return new mt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},t),this._requestOptions)}async countTokens(t,n={}){const o=ft(t,{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),n);return yt(this.apiKey,this.model,o,s)}async embedContent(t,n={}){const o=ht(t),s=Object.assign(Object.assign({},this._requestOptions),n);return Ct(this.apiKey,this.model,o,s)}async batchEmbedContents(t,n={}){const o=Object.assign(Object.assign({},this._requestOptions),n);return _t(this.apiKey,this.model,t,o)}}class oe{constructor(t){this.apiKey=t}getGenerativeModel(t,n){if(!t.model)throw new m("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new ne(this.apiKey,t,n)}getGenerativeModelFromCachedContent(t,n,o){if(!t.name)throw new _("Cached content must contain a `name` field.");if(!t.model)throw new _("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(n?.[a]&&t[a]&&n?.[a]!==t[a]){if(a==="model"){const c=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,u=t.model.startsWith("models/")?t.model.replace("models/",""):t.model;if(c===u)continue}throw new _(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${t[a]})`)}const i=Object.assign(Object.assign({},n),{model:t.model,tools:t.tools,toolConfig:t.toolConfig,systemInstruction:t.systemInstruction,cachedContent:t});return new ne(this.apiKey,i,o)}}function se(e,t){const n=Et(e),o=wt(n,t);return{tools:n,toolConfig:o}}function Et(e){let t=[];const n=[];return e.forEach(s=>{if(re(s)){const[i]=Be([s]);i.functionDeclarations&&t.push(...i.functionDeclarations)}else if(ce(s)){const{functionDeclarations:i}=vt(s);if(i)t.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(s)}),n.find(s=>"functionDeclarations"in s)?n.map(s=>{if(t?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...t]};return t=[],i}return s}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function vt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:E(e.function.parameters)}]}}function wt(e,t){if(!e.length||!t)return;const{toolChoice:n,allowedFunctionNames:o}=t,s={any:T.ANY,auto:T.AUTO,none:T.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:s[n]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof n=="string"||o)return{functionCallingConfig:{mode:T.ANY,allowedFunctionNames:[...o??[],...n&&typeof n=="string"?[n]:[]]}}}var St=class extends Se{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??Ae("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(n=>n.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 oe(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,t,n){this.apiKey&&(this.client=new oe(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}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,t){return this.withConfig({tools:se(e)?.tools,...t})}invocationParams(e){const t=e?.tools?.length?se(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),{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,n){const o=P(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(t);if(this.streaming){const r={},p=this._streamResponseChunks(e,t,n),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=$e(a.response,{usageMetadata:c});return u.generations?.length>0&&await n?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,t,n){const o=P(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(t),contents:s},c=await this.caller.callWithOptions({signal:t?.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&&t.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const y=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,y-r),r=y;const D=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,D-p),p=D;const G=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,G-f),f=G}const h=He(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await n?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e)}catch(n){throw n.message?.includes("400 Bad Request")&&(n.status=400),n}})}withStructuredOutput(e,t){const n=e,o=t?.name,s=t?.method,i=t?.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(ie(n)){const l=x(n);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new j({returnSingle:!0,keyName:f,zodSchema:n})}else{let l;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(l=n,l.parameters=E(n.parameters),f=n.name):l={name:f,description:n.description??"",parameters:E(n)},d=[{functionDeclarations:[l]}],c=new j({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=x(n);a=this.withConfig({responseSchema:f}),c=new Ne}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=U.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=U.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return be.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{St as ChatGoogleGenerativeAI};
|