@mcp-use/inspector 0.10.1 → 0.10.2-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-DhbomOzS.js → browser-BNks5xWz.js} +3 -3
- package/dist/client/assets/{display-A5IEINAP-BUdwu--X.js → display-A5IEINAP-C4F-HflA.js} +2 -2
- package/dist/client/assets/{embeddings-2-V6Dm5C.js → embeddings-CtLGleIr.js} +1 -1
- package/dist/client/assets/{index-BYhzDU5C.js → index-6GFlE05H.js} +1 -1
- package/dist/client/assets/{index-eSg28oTZ.js → index-BfP0MCNB.js} +1 -1
- package/dist/client/assets/{index-C0sILan8.js → index-C6wG5N14.js} +1 -1
- package/dist/client/assets/{index-BWh1LT8v.js → index-CoY4gjWM.js} +1 -1
- package/dist/client/assets/{index-Qp1UZyx2.js → index-CpwR_ExU.js} +6 -6
- package/dist/client/assets/{index-DnjTzXk7.js → index-CvLx60az.js} +1 -1
- package/dist/client/assets/{index-Ce878vOP.js → index-Dl3OHzka.js} +1 -1
- package/dist/client/assets/{index-DhgLWhgI.js → index-E2b6peCh.js} +1 -1
- package/dist/client/assets/{index-BP3EqGmh.js → index-IZmDP-4J.js} +1 -1
- package/dist/client/assets/{winston-DR7cYlm9.js → winston-CeUPKkjj.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,q as ve,Z as Ul,s as Fl,p as eo,u as g,a as dn,t as Rn,v as Xe,w as Vl,x as Or,y as Ms,z as Ps,A as Bl,B as Wl,C as Hl,D as zl}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-C4F-HflA.js","assets/index-CpwR_ExU.js","assets/index-BlKiZ9Yy.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,q as ve,Z as Ul,s as Fl,p as eo,u as g,a as dn,t as Rn,v as Xe,w as Vl,x as Or,y as Ms,z as Ps,A as Bl,B as Wl,C as Hl,D as zl}from"./index-CpwR_ExU.js";import{E as _g,F as bg,H as vg,L as Sg,G as Cg,M as Tg,W as kg,I as Eg}from"./index-CpwR_ExU.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-E2b6peCh.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{h as Tn,s as Zl,g as ro,B as Ql,k as ec,l as tc,I as nc,C as sc,m as rc,t as ic,n as oc,o as ac,p as lc,q as cc,r as uc,u as hc,v as dc,w as fc,x as pc,y as mc,R as gc,z as yc,a as wc}from"./index-6GFlE05H.js";import{aO as _c,aP as Ir,aQ as bc,at as xe,e as nn,aR as vc,aS as fn,a0 as fe,x as st,aT as io,g as Sc,aU as er,_ as q,ag as Xt,ae as oe,z as N,ad as ee,d as Cc,C as Tc,aV as kc,p as fi,aA as oo,aW as _e,ai as pn,aX as an,E as ao,y as Oe,aY as Rr,B as tr,D as Vt,am as Bt,aZ as Ec,a_ as xc,a$ as Ac,b0 as Mc,b1 as Pc,b2 as Nc,b3 as Oc,b4 as Ic,b5 as Rc,b6 as $c,b7 as jc,b8 as Lc,b9 as Dc,ba as Uc,bb as Fc,bc as Vc,bd as Bc,K as Wc,be as Hc,bf as zc,bg as Gc,t as Le,r as ln,m as $e,L as Ze,aq as Wt,bh as Kc,F as Jc,aB as pi,ar as qc,bi as mi,bj as gi,ab as $r,aa as yi,a9 as nr,ac as Yc,S as Xc,a5 as jr,a8 as Ke,bk as ts,o as W,bl as le,bm as Zc,bn as Me,bo as vt,bp as Qc,bq as Lr,l as U,a6 as eu,i as tu,T as nu,br as ns,bs as Fe,bt as F,bu as lo,s as ne,a7 as su,bv as $n,bw as co,bx as Ht,by as mn,bz as ss,bA as rs,bB as ru,aK as iu,aI as ou,aH as au,bC as lu}from"./index-Dl3OHzka.js";import{E as uo,c as cu,e as uu}from"./embeddings-CtLGleIr.js";import"./index-DRz5BQNA.js";var Ns,An,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=An)),i==null||o==null){var a=t.random||(t.rng||_c)();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,An===void 0&&!t._v6&&(An=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,An=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"?bc(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,gg=(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 A of v.tool_calls){const E=A.name||"unknown",P=A.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 A=v.content;let E=String(A);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-BUdwu--X.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,gg=(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 A of v.tool_calls){const E=A.name||"unknown",P=A.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 A=v.content;let E=String(A);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-C4F-HflA.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-CvLx60az.js","assets/index-CpwR_ExU.js","assets/index-BlKiZ9Yy.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as a,a as k}from"./index-CpwR_ExU.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-CvLx60az.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-Dl3OHzka.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 Be,N as Ue,O as X,P as te,_ as U,Q as At,S as Ot,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,n as Dt,$ as Lt,g as Ce,a0 as Ft,a1 as Bt,a2 as Ut,a3 as jt,a4 as Vt,a5 as zt,a6 as Gt,i as $t,a7 as Zt,h as Ge,a8 as Ht,a9 as $e,aa as Wt,ab as Xt,ac as Yt,ad as H,x as ue,ae as Se,af as Jt,ag as Kt,ah as qt,A as Ze,ai as ne,e as ie,aj as He,ak as We,b as oe,K as Qt,C as be,al as je,c as ea,R as Ve,y as Y,a as ta,am as Ie,D as aa,L as Xe,an as sa,ao as na,ap as ra,z as Ye,aq as re,r as G,ar as Je,as as ia,at as Ke,u as oa,m as ca,au as ua,av as la,aw as ha,ax as pa,ay as ga,az as ma,aA as fa,aB as da,B as ze,aC as ba,G as _a,aD as ya,o as qe,s as Qe,aE as Ta,aF as Te,p as va}from"./index-Ce878vOP.js";import{g as Ea}from"./index-Qp1UZyx2.js";import{r as wa}from"./index-DRz5BQNA.js";function et(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Be(a),h=Be(e),l=!1,m=h.length-1;m>=0;m--){var g=h[m],T=e[g];if(Ue(a,g)&&!(a[g]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[g];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?et(T,_,n,r+"/"+X(g),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"replace",path:r+"/"+X(g),value:te(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"remove",path:r+"/"+X(g)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var m=0;m<c.length;m++){var g=c[m];!Ue(e,g)&&a[g]!==void 0&&n.push({op:"add",path:r+"/"+X(g),value:te(a[g])})}}}function Ae(e,a,n=!1){var r=[];return et(e,a,r,"",n),r}var Ca={};U(Ca,{extendInteropZodObject:()=>Yt,getInteropZodDefaultGetter:()=>Xt,getInteropZodObjectShape:()=>Wt,getSchemaDescription:()=>$e,interopParse:()=>Ht,interopParseAsync:()=>Ge,interopSafeParse:()=>Zt,interopSafeParseAsync:()=>$t,interopZodObjectMakeFieldsOptional:()=>Gt,interopZodObjectPartial:()=>zt,interopZodObjectPassthrough:()=>Vt,interopZodObjectStrict:()=>jt,interopZodTransformInputSchema:()=>Ut,isInteropZodLiteral:()=>Bt,isInteropZodObject:()=>Ft,isInteropZodSchema:()=>Ce,isShapelessZodSchema:()=>Lt,isSimpleStringZodSchema:()=>Dt,isZodArrayV4:()=>Rt,isZodLiteralV3:()=>Mt,isZodLiteralV4:()=>Pt,isZodObjectV3:()=>xt,isZodObjectV4:()=>kt,isZodSchema:()=>Nt,isZodSchemaV3:()=>Ot,isZodSchemaV4:()=>At});function tt(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function at(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function st(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ce(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function nt(e){return st(e)||at(e)||tt(e)}var Sa={};U(Sa,{convertToOpenAIFunction:()=>rt,convertToOpenAITool:()=>Ia,isLangChainTool:()=>nt,isRunnableToolLike:()=>at,isStructuredTool:()=>tt,isStructuredToolParams:()=>st});function rt(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:ue(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ia(e,a){const n=typeof a=="number"?void 0:a;let r;return nt(e)?r={type:"function",function:rt(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Aa={};U(Aa,{BasePromptValue:()=>le,ChatPromptValue:()=>ot,ImagePromptValue:()=>Oa,StringPromptValue:()=>it});var le=class extends Kt{},it=class extends le{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ot=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Jt(this.messages)}toChatMessages(){return this.messages}},Oa=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},b="0123456789abcdef".split(""),Na=[-2147483648,8388608,32768,128],F=[24,16,8,0],ae=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],k=[];function B(e,a){a?(k[0]=k[16]=k[1]=k[2]=k[3]=k[4]=k[5]=k[6]=k[7]=k[8]=k[9]=k[10]=k[11]=k[12]=k[13]=k[14]=k[15]=0,this.blocks=k):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<F[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<F[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<F[c++&3],l[c>>>2]|=(128|r>>>12&63)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Na[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=this.blocks,g,T,_,v,d,y,f,E,w,P,I;for(g=16;g<64;++g)d=m[g-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=m[g-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,m[g]=m[g-16]+T+m[g-7]+_<<0;for(I=a&n,g=0;g<64;g+=4)this.first?(this.is224?(E=300032,d=m[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(E=704751109,d=m[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),E=e&a,v=E^e&n^I,f=i&c^~i&h,d=l+_+f+ae[g]+m[g],y=T+v,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,v=w^r&a^E,f=h&l^~h&i,d=c+_+f+ae[g+1]+m[g+1],y=T+v,h=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),P=n&r,v=P^n&e^w,f=c&h^~c&l,d=i+_+f+ae[g+2]+m[g+2],y=T+v,c=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),I=a&n,v=I^a&r^P,f=c&h^~c&l,d=i+_+f+ae[g+3]+m[g+3],y=T+v,i=e+d<<0,e=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=b[e>>>28&15]+b[e>>>24&15]+b[e>>>20&15]+b[e>>>16&15]+b[e>>>12&15]+b[e>>>8&15]+b[e>>>4&15]+b[e&15]+b[a>>>28&15]+b[a>>>24&15]+b[a>>>20&15]+b[a>>>16&15]+b[a>>>12&15]+b[a>>>8&15]+b[a>>>4&15]+b[a&15]+b[n>>>28&15]+b[n>>>24&15]+b[n>>>20&15]+b[n>>>16&15]+b[n>>>12&15]+b[n>>>8&15]+b[n>>>4&15]+b[n&15]+b[r>>>28&15]+b[r>>>24&15]+b[r>>>20&15]+b[r>>>16&15]+b[r>>>12&15]+b[r>>>8&15]+b[r>>>4&15]+b[r&15]+b[i>>>28&15]+b[i>>>24&15]+b[i>>>20&15]+b[i>>>16&15]+b[i>>>12&15]+b[i>>>8&15]+b[i>>>4&15]+b[i&15]+b[c>>>28&15]+b[c>>>24&15]+b[c>>>20&15]+b[c>>>16&15]+b[c>>>12&15]+b[c>>>8&15]+b[c>>>4&15]+b[c&15]+b[h>>>28&15]+b[h>>>24&15]+b[h>>>20&15]+b[h>>>16&15]+b[h>>>12&15]+b[h>>>8&15]+b[h>>>4&15]+b[h&15];return this.is224||(m+=b[l>>>28&15]+b[l>>>24&15]+b[l>>>20&15]+b[l>>>16&15]+b[l>>>12&15]+b[l>>>8&15]+b[l>>>4&15]+b[l&15]),m};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||m.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),m};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const ct=(...e)=>new B(!1,!0).update(e.join("")).hex();var ka={};U(ka,{sha256:()=>ct});var xa={};U(xa,{BaseCache:()=>lt,InMemoryCache:()=>ht,defaultHashKeyEncoder:()=>ut,deserializeStoredGeneration:()=>Pa,serializeGeneration:()=>Ma});const ut=(...e)=>ct(e.join("_"));function Pa(e){return e.message!==void 0?{text:e.text,message:qt(e.message)}:{text:e.text}}function Ma(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var lt=class{keyEncoder=ut;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ra=new Map;var ht=class pt extends lt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new pt(Ra)}},Da=wa();const La=Ea(Da);var Fa=Object.defineProperty,Ba=(e,a,n)=>a in e?Fa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,Ua=(e,a,n)=>(Ba(e,a+"",n),n);function ja(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Va(e,a){return e.length===1?[a.get(e.join(","))]:ja(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function za(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var ve=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
|
|
1
|
+
import{M as Be,N as Ue,O as X,P as te,_ as U,Q as At,S as Ot,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,n as Dt,$ as Lt,g as Ce,a0 as Ft,a1 as Bt,a2 as Ut,a3 as jt,a4 as Vt,a5 as zt,a6 as Gt,i as $t,a7 as Zt,h as Ge,a8 as Ht,a9 as $e,aa as Wt,ab as Xt,ac as Yt,ad as H,x as ue,ae as Se,af as Jt,ag as Kt,ah as qt,A as Ze,ai as ne,e as ie,aj as He,ak as We,b as oe,K as Qt,C as be,al as je,c as ea,R as Ve,y as Y,a as ta,am as Ie,D as aa,L as Xe,an as sa,ao as na,ap as ra,z as Ye,aq as re,r as G,ar as Je,as as ia,at as Ke,u as oa,m as ca,au as ua,av as la,aw as ha,ax as pa,ay as ga,az as ma,aA as fa,aB as da,B as ze,aC as ba,G as _a,aD as ya,o as qe,s as Qe,aE as Ta,aF as Te,p as va}from"./index-Dl3OHzka.js";import{g as Ea}from"./index-CpwR_ExU.js";import{r as wa}from"./index-DRz5BQNA.js";function et(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Be(a),h=Be(e),l=!1,m=h.length-1;m>=0;m--){var g=h[m],T=e[g];if(Ue(a,g)&&!(a[g]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[g];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?et(T,_,n,r+"/"+X(g),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"replace",path:r+"/"+X(g),value:te(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"remove",path:r+"/"+X(g)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var m=0;m<c.length;m++){var g=c[m];!Ue(e,g)&&a[g]!==void 0&&n.push({op:"add",path:r+"/"+X(g),value:te(a[g])})}}}function Ae(e,a,n=!1){var r=[];return et(e,a,r,"",n),r}var Ca={};U(Ca,{extendInteropZodObject:()=>Yt,getInteropZodDefaultGetter:()=>Xt,getInteropZodObjectShape:()=>Wt,getSchemaDescription:()=>$e,interopParse:()=>Ht,interopParseAsync:()=>Ge,interopSafeParse:()=>Zt,interopSafeParseAsync:()=>$t,interopZodObjectMakeFieldsOptional:()=>Gt,interopZodObjectPartial:()=>zt,interopZodObjectPassthrough:()=>Vt,interopZodObjectStrict:()=>jt,interopZodTransformInputSchema:()=>Ut,isInteropZodLiteral:()=>Bt,isInteropZodObject:()=>Ft,isInteropZodSchema:()=>Ce,isShapelessZodSchema:()=>Lt,isSimpleStringZodSchema:()=>Dt,isZodArrayV4:()=>Rt,isZodLiteralV3:()=>Mt,isZodLiteralV4:()=>Pt,isZodObjectV3:()=>xt,isZodObjectV4:()=>kt,isZodSchema:()=>Nt,isZodSchemaV3:()=>Ot,isZodSchemaV4:()=>At});function tt(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function at(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function st(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ce(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function nt(e){return st(e)||at(e)||tt(e)}var Sa={};U(Sa,{convertToOpenAIFunction:()=>rt,convertToOpenAITool:()=>Ia,isLangChainTool:()=>nt,isRunnableToolLike:()=>at,isStructuredTool:()=>tt,isStructuredToolParams:()=>st});function rt(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:ue(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ia(e,a){const n=typeof a=="number"?void 0:a;let r;return nt(e)?r={type:"function",function:rt(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Aa={};U(Aa,{BasePromptValue:()=>le,ChatPromptValue:()=>ot,ImagePromptValue:()=>Oa,StringPromptValue:()=>it});var le=class extends Kt{},it=class extends le{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ot=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Jt(this.messages)}toChatMessages(){return this.messages}},Oa=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},b="0123456789abcdef".split(""),Na=[-2147483648,8388608,32768,128],F=[24,16,8,0],ae=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],k=[];function B(e,a){a?(k[0]=k[16]=k[1]=k[2]=k[3]=k[4]=k[5]=k[6]=k[7]=k[8]=k[9]=k[10]=k[11]=k[12]=k[13]=k[14]=k[15]=0,this.blocks=k):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<F[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<F[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<F[c++&3],l[c>>>2]|=(128|r>>>12&63)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Na[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=this.blocks,g,T,_,v,d,y,f,E,w,P,I;for(g=16;g<64;++g)d=m[g-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=m[g-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,m[g]=m[g-16]+T+m[g-7]+_<<0;for(I=a&n,g=0;g<64;g+=4)this.first?(this.is224?(E=300032,d=m[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(E=704751109,d=m[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),E=e&a,v=E^e&n^I,f=i&c^~i&h,d=l+_+f+ae[g]+m[g],y=T+v,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,v=w^r&a^E,f=h&l^~h&i,d=c+_+f+ae[g+1]+m[g+1],y=T+v,h=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),P=n&r,v=P^n&e^w,f=c&h^~c&l,d=i+_+f+ae[g+2]+m[g+2],y=T+v,c=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),I=a&n,v=I^a&r^P,f=c&h^~c&l,d=i+_+f+ae[g+3]+m[g+3],y=T+v,i=e+d<<0,e=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=b[e>>>28&15]+b[e>>>24&15]+b[e>>>20&15]+b[e>>>16&15]+b[e>>>12&15]+b[e>>>8&15]+b[e>>>4&15]+b[e&15]+b[a>>>28&15]+b[a>>>24&15]+b[a>>>20&15]+b[a>>>16&15]+b[a>>>12&15]+b[a>>>8&15]+b[a>>>4&15]+b[a&15]+b[n>>>28&15]+b[n>>>24&15]+b[n>>>20&15]+b[n>>>16&15]+b[n>>>12&15]+b[n>>>8&15]+b[n>>>4&15]+b[n&15]+b[r>>>28&15]+b[r>>>24&15]+b[r>>>20&15]+b[r>>>16&15]+b[r>>>12&15]+b[r>>>8&15]+b[r>>>4&15]+b[r&15]+b[i>>>28&15]+b[i>>>24&15]+b[i>>>20&15]+b[i>>>16&15]+b[i>>>12&15]+b[i>>>8&15]+b[i>>>4&15]+b[i&15]+b[c>>>28&15]+b[c>>>24&15]+b[c>>>20&15]+b[c>>>16&15]+b[c>>>12&15]+b[c>>>8&15]+b[c>>>4&15]+b[c&15]+b[h>>>28&15]+b[h>>>24&15]+b[h>>>20&15]+b[h>>>16&15]+b[h>>>12&15]+b[h>>>8&15]+b[h>>>4&15]+b[h&15];return this.is224||(m+=b[l>>>28&15]+b[l>>>24&15]+b[l>>>20&15]+b[l>>>16&15]+b[l>>>12&15]+b[l>>>8&15]+b[l>>>4&15]+b[l&15]),m};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||m.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),m};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const ct=(...e)=>new B(!1,!0).update(e.join("")).hex();var ka={};U(ka,{sha256:()=>ct});var xa={};U(xa,{BaseCache:()=>lt,InMemoryCache:()=>ht,defaultHashKeyEncoder:()=>ut,deserializeStoredGeneration:()=>Pa,serializeGeneration:()=>Ma});const ut=(...e)=>ct(e.join("_"));function Pa(e){return e.message!==void 0?{text:e.text,message:qt(e.message)}:{text:e.text}}function Ma(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var lt=class{keyEncoder=ut;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ra=new Map;var ht=class pt extends lt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new pt(Ra)}},Da=wa();const La=Ea(Da);var Fa=Object.defineProperty,Ba=(e,a,n)=>a in e?Fa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,Ua=(e,a,n)=>(Ba(e,a+"",n),n);function ja(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Va(e,a){return e.length===1?[a.get(e.join(","))]:ja(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function za(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var ve=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
|
|
2
2
|
`).filter(Boolean).reduce((r,i)=>{const[c,h,...l]=i.split(" "),m=Number.parseInt(h,10);return l.forEach((g,T)=>r[g]=m+T),r},{});for(const[r,i]of Object.entries(n)){const c=La.toByteArray(r);this.rankMap.set(c.join(","),i),this.textMap.set(i,c)}this.specialTokens={...e.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[i,c])=>(r[c]=this.textEncoder.encode(i),r),{})}encode(e,a=[],n="all"){const r=new RegExp(this.patStr,"ug"),i=ve.specialTokenRegex(Object.keys(this.specialTokens)),c=[],h=new Set(a==="all"?Object.keys(this.specialTokens):a),l=new Set(n==="all"?Object.keys(this.specialTokens).filter(g=>!h.has(g)):n);if(l.size>0){const g=ve.specialTokenRegex([...l]),T=e.match(g);if(T!=null)throw new Error(`The text contains a special token that is not allowed: ${T[0]}`)}let m=0;for(;;){let g=null,T=m;for(;i.lastIndex=T,g=i.exec(e),!(g==null||h.has(g[0]));)T=g.index+1;const _=g?.index??e.length;for(const d of e.substring(m,_).matchAll(r)){const y=this.textEncoder.encode(d[0]),f=this.rankMap.get(y.join(","));if(f!=null){c.push(f);continue}c.push(...Va(y,this.rankMap))}if(g==null)break;let v=this.specialTokens[g[0]];c.push(v),m=g.index+g[0].length}return c}decode(e){const a=[];let n=0;for(let c=0;c<e.length;++c){const h=e[c],l=this.textMap.get(h)??this.inverseSpecialTokens[h];l!=null&&(a.push(l),n+=l.length)}const r=new Uint8Array(n);let i=0;for(const c of a)r.set(c,i),i+=c.length;return this.textDecoder.decode(r)}},gt=ve;Ua(gt,"specialTokenRegex",e=>new RegExp(e.map(a=>za(a)).join("|"),"g"));function Ga(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var $a={};U($a,{encodingForModel:()=>Oe,getEncoding:()=>mt});const se={},Za=new Ze({});async function mt(e){return e in se||(se[e]=Za.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(a=>a.json()).then(a=>new gt(a)).catch(a=>{throw delete se[e],a})),await se[e]}async function Oe(e){return mt(Ga(e))}var Ha={};U(Ha,{BaseLangChain:()=>dt,BaseLanguageModel:()=>bt,calculateMaxTokens:()=>Ya,getEmbeddingContextSize:()=>Wa,getModelContextSize:()=>ft,getModelNameForTiktoken:()=>he,isOpenAITool:()=>Xa});const he=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Wa=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},ft=e=>{switch(he(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Xa(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const Ya=async({prompt:e,modelName:a})=>{let n;try{n=(await Oe(he(a))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return ft(a)-n},Ja=()=>!1;var dt=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Ja(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},bt=class extends dt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:a,...n}){const{cache:r,...i}=n;super({callbacks:e??a,...i}),typeof r=="object"?this.cache=r:r?this.cache=ht.global():this.cache=void 0,this.caller=new Ze(n??{})}_encoding;async getNumTokens(e){let a;typeof e=="string"?a=e:a=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await Oe("modelName"in this?he(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new it(e):Array.isArray(e)?new ot(e.map(ne)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([c,h])=>h!==void 0).map(([c,h])=>`${c}:${JSON.stringify(h)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}},ce=class extends H{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,a){const n=ie(a);return this.func&&await this.func(e,n),this._callWithConfig(r=>Promise.resolve(r),e,n)}async*transform(e,a){const n=ie(a);let r,i=!0;for await(const c of this._transformStreamWithConfig(e,h=>h,n))if(yield c,i)if(r===void 0)r=c;else try{r=oe(r,c)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new He(new We({steps:e}))}};const Ka=e=>e();function _e(e){const a=e.constructor;return new a({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var qa={};U(qa,{BaseChatModel:()=>_t,SimpleChatModel:()=>Qa});function ye(e){const a=[];for(const n of e){let r=n;if(Array.isArray(n.content))for(let i=0;i<n.content.length;i++){const c=n.content[i];(sa(c)||na(c))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,i),ra(c),...n.content.slice(i+1)]}))}a.push(r)}return a}var _t=class $ extends bt{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=Ka(()=>{const n=a.outputVersion??Qt("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=$._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===$.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const i=$._convertInputToPromptValue(a).toChatMessages(),[c,h]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...c.metadata,...this.getLsParams(h)},m=await be.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),g={options:h,invocation_params:this?.invocationParams(h),batch_size:1},T=h.outputVersion??this.outputVersion,_=await m?.handleChatModelStart(this.toJSON(),[ye(i)],c.runId,void 0,g,void 0,void 0,c.runName);let v,d;try{for await(const y of this._streamResponseChunks(i,h,_?.[0])){if(y.message.id==null){const f=_?.at(0)?.runId;f!=null&&y.message._updateId(`run-${f}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},T==="v1"?yield _e(y.message):yield y.message,v?v=v.concat(y):v=y,je(y.message)&&y.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}}catch(y){throw await Promise.all((_??[]).map(f=>f?.handleLLMError(y))),y}await Promise.all((_??[]).map(y=>y?.handleLLMEnd({generations:[[v]],llmOutput:d})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,i){const c=a.map(v=>v.map(ne));let h;if(i!==void 0&&i.length===c.length)h=i;else{const v={...r.metadata,...this.getLsParams(n)},d=await be.configure(r.callbacks,this.callbacks,r.tags,this.tags,v,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};h=await d?.handleChatModelStart(this.toJSON(),c.map(ye),r.runId,void 0,y,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,m=[],g=[];if(!!h?.[0].handlers.find(ea)&&!this.disableStreaming&&c.length===1&&this._streamResponseChunks!==$.prototype._streamResponseChunks)try{const v=await this._streamResponseChunks(c[0],n,h?.[0]);let d,y;for await(const f of v){if(f.message.id==null){const E=h?.at(0)?.runId;E!=null&&f.message._updateId(`run-${E}`)}d===void 0?d=f:d=oe(d,f),je(f.message)&&f.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");m.push([d]),await h?.[0].handleLLMEnd({generations:m,llmOutput:y})}catch(v){throw await h?.[0].handleLLMError(v),v}else{const v=await Promise.allSettled(c.map(async(d,y)=>{const f=await this._generate(d,{...n,promptIndex:y},h?.[y]);if(l==="v1")for(const E of f.generations)E.message=_e(E.message);return f}));await Promise.all(v.map(async(d,y)=>{if(d.status==="fulfilled"){const f=d.value;for(const E of f.generations){if(E.message.id==null){const w=h?.at(0)?.runId;w!=null&&E.message._updateId(`run-${w}`)}E.message.response_metadata={...E.generationInfo,...E.message.response_metadata}}return f.generations.length===1&&(f.generations[0].message.response_metadata={...f.llmOutput,...f.generations[0].message.response_metadata}),m[y]=f.generations,g[y]=f.llmOutput,h?.[y]?.handleLLMEnd({generations:[f.generations],llmOutput:f.llmOutput})}else return await h?.[y]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}const _={generations:m,llmOutput:g.length?this._combineLLMOutput?.(...g):void 0};return Object.defineProperty(_,Ve,{value:h?{runIds:h?.map(v=>v.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:c}){const h=a.map(w=>w.map(ne)),l={...c.metadata,...this.getLsParams(i)},m=await be.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),g={options:i,invocation_params:this?.invocationParams(i),batch_size:1},T=await m?.handleChatModelStart(this.toJSON(),h.map(ye),c.runId,void 0,g,void 0,void 0,c.runName),_=[],d=(await Promise.allSettled(h.map(async(w,P)=>{const I=$._convertInputToPromptValue(w).toString(),R=await n.lookup(I,r);return R==null&&_.push(P),R}))).map((w,P)=>({result:w,runManager:T?.[P]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),y=i.outputVersion??this.outputVersion,f=[];await Promise.all(d.map(async({result:w,runManager:P},I)=>{if(w.status==="fulfilled"){const R=w.value;return f[I]=R.map(L=>("message"in L&&Y(L.message)&&ta(L.message)&&(L.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(L.message=_e(L.message))),L.generationInfo={...L.generationInfo,tokenUsage:{}},L)),R.length&&await P?.handleLLMNewToken(R[0].text),P?.handleLLMEnd({generations:[R]},void 0,void 0,void 0,{cached:!0})}else return await P?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const E={generations:f,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(E,Ve,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),E}async generate(a,n,r){let i;Array.isArray(n)?i={stop:n}:i=n;const c=a.map(y=>y.map(ne)),[h,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(h.callbacks=h.callbacks??r,!this.cache)return this._generateUncached(c,l,h);const{cache:m}=this,g=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:v}=await this._generateCached({messages:c,cache:m,llmStringKey:g,parsedOptions:l,handledOptions:h});let d={};if(_.length>0){const y=await this._generateUncached(_.map(f=>c[f]),l,h,v!==void 0?_.map(f=>v?.[f]):void 0);await Promise.all(y.generations.map(async(f,E)=>{const w=_[E];T[w]=f;const P=$._convertInputToPromptValue(c[w]).toString();return m.update(P,g,f)})),d=y.llmOutput??{}}return{generations:T,llmOutput:d}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const i=a.map(c=>c.toChatMessages());return this.generate(i,n,r)}withStructuredOutput(a,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=a,i=n?.name,c=$e(r)??"A function available to call.",h=n?.method,l=n?.includeRaw;if(h==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let m=i??"extract",g;Ce(r)?g=[{type:"function",function:{name:m,description:c,parameters:ue(r)}}]:("name"in r&&(m=r.name),g=[{type:"function",function:{name:m,description:c,parameters:r}}]);const T=this.bindTools(g),_=Ie.from(f=>{if(!aa.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const E=f.tool_calls.find(w=>w.name===m);if(!E)throw new Error(`No tool call found with name ${m}.`);return E.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const v=ce.assign({parsed:(f,E)=>_.invoke(f.raw,E)}),d=ce.assign({parsed:()=>null}),y=v.withFallbacks({fallbacks:[d]});return Xe.from([{raw:T},y]).withConfig({runName:"StructuredOutputRunnable"})}},Qa=class extends _t{async _generate(e,a,n){const r=await this._call(e,a,n),i=new Ye(r);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}},es=class extends H{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.invoke(r,ie(a))}async batch(e,a,n){const r=e.map(_=>_.key),i=e.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const h=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},e.length),m=l[0]?.maxConcurrency??n?.maxConcurrency,g=m&&m>0?m:e.length,T=[];for(let _=0;_<i.length;_+=g){const v=i.slice(_,_+g).map((y,f)=>h[f].invoke(y,l[f])),d=await Promise.all(v);T.push(d)}return T.flat()}async stream(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.stream(r,a)}},ts=class extends H{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([i,c])=>[re(i),re(c)]),r=re(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,a,n){let r;for(let i=0;i<this.branches.length;i+=1){const[c,h]=this.branches[i];if(await c.invoke(e,G(a,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await h.invoke(e,G(a,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||(r=await this.default.invoke(e,G(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(e,a={}){return this._callWithConfig(this._invoke,e,a)}async*_streamIterator(e,a){const r=await(await Je(a))?.handleChainStart(this.toJSON(),ia(e,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let i,c=!0,h;try{for(let l=0;l<this.branches.length;l+=1){const[m,g]=this.branches[l];if(await m.invoke(e,G(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){h=await g.stream(e,G(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of h)if(yield _,c)if(i===void 0)i=_;else try{i=oe(i,_)}catch{i=void 0,c=!1}break}}if(h===void 0){h=await this.default.stream(e,G(a,{callbacks:r?.getChild("branch:default")}));for await(const l of h)if(yield l,c)if(i===void 0)i=l;else try{i=oe(i,l)}catch{i=void 0,c=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(i??{})}},as=class extends Ke{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let a=Ie.from((c,h)=>this._enterHistory(c,h??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(a=ce.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(e.runnable.withListeners({onEnd:(c,h)=>this._exitHistory(c,h??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let a;if(typeof e=="object"&&!Array.isArray(e)&&!Y(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?a=e[n][0]:a=e[n]}else a=e;if(typeof a=="string")return[new Se(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
|
|
3
3
|
Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(e){let a;if(!Array.isArray(e)&&!Y(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?a=e.generations[0][0].message:a=e[n]}else a=e;if(typeof a=="string")return[new Ye(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(e,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,a){const n=a.configurable?.messageHistory;let r;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?r=e.inputs[0]:r=e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();i=i.slice(l.length)}const c=e.outputs;if(!c)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const h=this._getOutputMessages(c);await n.addMessages([...i,...h])}async _mergeConfig(...e){const a=await super._mergeConfig(...e);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
|
|
4
4
|
eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(i)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},ss={};U(ss,{RouterRunnable:()=>es,Runnable:()=>H,RunnableAssign:()=>He,RunnableBinding:()=>Ke,RunnableBranch:()=>ts,RunnableEach:()=>ma,RunnableLambda:()=>Ie,RunnableMap:()=>We,RunnableParallel:()=>ga,RunnablePassthrough:()=>ce,RunnablePick:()=>pa,RunnableRetry:()=>ha,RunnableSequence:()=>Xe,RunnableToolLike:()=>la,RunnableWithFallbacks:()=>ua,RunnableWithMessageHistory:()=>as,_coerceToRunnable:()=>re,ensureConfig:()=>ie,getCallbackManagerForConfig:()=>Je,mergeConfigs:()=>ca,patchConfig:()=>G,pickRunnableConfigKeys:()=>oa});var yt=class extends H{parseResultWithPrompt(e,a,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,a){return typeof e=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),e,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),e,{...a,runType:"parser"})}},pe=class extends yt{parseResult(e,a){return this.parse(e[0].text,a)}async parseWithPrompt(e,a,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},Z=class extends Error{llmOutput;observation;sendToLLM;constructor(e,a,n,r=!1){if(super(e),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fa(this,"OUTPUT_PARSING_FAILURE")}},q=class extends pe{async*_transform(e){for await(const a of e)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(e,a){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...a,runType:"parser"})}},Ne=class extends q{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let a,n;for await(const r of e){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let i;if(da(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new ze({message:r,text:r.content})}else if(Y(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new ze({message:ba(r),text:r.content})}else i=new _a({text:r});n===void 0?n=i:n=n.concat(i);const c=await this.parsePartialResult([n]);c!=null&&!ya(c,a)&&(this.diff?yield this._diff(a,c):yield c,a=c)}}getFormatInstructions(){return""}},ns=class extends q{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},Q=class extends q{re;async*_transform(e){let a="";for await(const n of e)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let i=0;for(const c of r.slice(0,-1))yield[c[1]],i+=(c.index??0)+c[0].length;a=a.slice(i)}}else{const r=await this.parse(a);if(r.length>1){for(const i of r.slice(0,-1))yield[i];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},rs=class extends Q{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(a=>a.trim())}catch{throw new Z(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},is=class extends Q{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:a}){super(...arguments),this.length=e,this.separator=a||","}async parse(e){try{const a=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new Z(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===Z.prototype?a:new Z(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},os=class extends Q{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{E as Ss,aG as S,S as xa,Q as ka,K as jn,g as Ke,x as Ze,a9 as Sa,am as Aa,L as Ca,H as As,I as Cs,z as ke,l as Os,aH as Oa,D as cn,aI as Ln,aJ as Ia,aK as Ta,aL as Ra,J as Dn,aM as Fn,aN as $a,B as Jt,a as Pa}from"./index-
|
|
1
|
+
import{E as Ss,aG as S,S as xa,Q as ka,K as jn,g as Ke,x as Ze,a9 as Sa,am as Aa,L as Ca,H as As,I as Cs,z as ke,l as Os,aH as Oa,D as cn,aI as Ln,aJ as Ia,aK as Ta,aL as Ra,J as Dn,aM as Fn,aN as $a,B as Jt,a as Pa}from"./index-Dl3OHzka.js";import{e as Ea,j as Ma,h as Na,f as Is,S as Bn,J as Un,R as Wn}from"./index-6GFlE05H.js";import{t as Ts,d as ja}from"./index-CpwR_ExU.js";import{J as qn,c as La,p as Rs,m as Kt}from"./index-E2b6peCh.js";import"./embeddings-CtLGleIr.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 Ea(t)?n=Ma(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($s(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
2
2
|
`)}function $s(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["{",$s(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{e as at,f as rt,g as mt,O as Ct,h as Ot,J as yt,R as G}from"./index-BYhzDU5C.js";import{g as ut,x as It,y as vt,z as _t,B as Et,D as Tt,E as wt,F as St,a as lt,H as Rt,I as At,J as x,i as xt,K as kt,L as Nt}from"./index-Ce878vOP.js";import"./embeddings-2-V6Dm5C.js";import"./index-Qp1UZyx2.js";import"./index-DRz5BQNA.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const e=I(ut(t)?It(t):t),{$schema:n,...s}=e;return s}function bt(t){const e=I(t),{$schema:n,...s}=e;return s}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Mt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let k;const Dt=new Uint8Array(16);function Gt(){if(!k){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k=crypto.getRandomValues.bind(crypto)}return k(Dt)}const Ut=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Ut};function ct(t,e,n){if(U.randomUUID&&!t)return U.randomUUID();t=t||{};const s=t.random??t.rng?.()??Gt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Mt(s)}const b="__gemini_function_call_thought_signatures__",Lt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Pt=t=>t();function jt(t){const e=t._getType();return wt.isInstance(t)?t.role:e==="tool"?e:t.name??e}function Ft(t){switch(t){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: ${t}`)}}function Kt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Ht(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function $t(t){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!t)throw new Error("This model does not support images");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.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(!t)throw new Error("This model does not support audio");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.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(!t)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.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(t,e){if(Rt(t))return At(t,$t(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return Kt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function Yt(t,e,n,s){if(St(t)){const u=t.name??Ht(t,n);if(u===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 "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const c=Array.isArray(t.content)?t.content.map(p=>L(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:c}}}}]:[{functionResponse:{name:u,response:{result:c}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>L(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[b];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const c=Pt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?Lt:""});return{functionCall:{name:u.name,args:u.args},...c?{thoughtSignature:c}:{}}})),[...o,...i]}function P(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!vt(o))throw new Error("Unsupported message input");const u=jt(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const c=Ft(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Yt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const d=i.content[i.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:i.content}}let l=c;(l==="function"||l==="system"&&!n)&&(l="user");const f={role:l,parts:r};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function Bt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);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=[];const u=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(l=>"text"in l)?.text??c),{generations:[{text:c,message:new _t({content:a??"",tool_calls:o?.map(r=>({type:"tool_call",id:r.id,name:r.functionCall.name,args:r.functionCall.args})),additional_kwargs:{...i,[b]:u},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function qt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);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 u="";a&&typeof a=="string"?u=a:Array.isArray(a)&&(u=a.find(l=>"text"in l)?.text??"");const c=[];o&&c.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const p=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});return new Et({text:u,message:new Tt({content:a||"",name:s?s.role:void 0,tool_call_chunks:c,additional_kwargs:{[b]:p},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Wt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:n}}return rt(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:bt(e.function.parameters)}:e})}]}function j(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends mt{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await xt(this.zodSchema,t);if(e.success)return e.data;throw new Ct(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(i=>{const{message:o}=i;return!("tool_calls"in o)||!Array.isArray(o.tool_calls)?[]:o.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},K;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(K||(K={}));var H;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(H||(H={}));var $;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const Y=["user","model","function","system"];var B;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(B||(B={}));var q;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(q||(q={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var V;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(V||(V={}));var T;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(T||(T={}));var J;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(J||(J={}));var E;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(E||(E={}));var z;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(z||(z={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class dt extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class ft extends m{}const Vt="https://generativelanguage.googleapis.com",Jt="v1beta",zt="0.24.1",Zt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Qt{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Jt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Vt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function Xt(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Zt}/${zt}`),e.join(" ")}async function te(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function ee(t,e,n,s,i,o){const a=new Qt(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},oe(o)),{method:"POST",headers:await te(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:c}=await ee(t,e,n,s,i,o);return ne(u,c,a)}async function ne(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){se(i,t)}return s.ok||await ie(s,t),s}function se(t,e){let n=t;throw n.name==="AbortError"?(n=new ft(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof dt||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ie(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new dt(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function oe(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function M(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return ae(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ae(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
|
|
1
|
+
import{e as at,f as rt,g as mt,O as Ct,h as Ot,J as yt,R as G}from"./index-6GFlE05H.js";import{g as ut,x as It,y as vt,z as _t,B as Et,D as Tt,E as wt,F as St,a as lt,H as Rt,I as At,J as x,i as xt,K as kt,L as Nt}from"./index-Dl3OHzka.js";import"./embeddings-CtLGleIr.js";import"./index-CpwR_ExU.js";import"./index-DRz5BQNA.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const e=I(ut(t)?It(t):t),{$schema:n,...s}=e;return s}function bt(t){const e=I(t),{$schema:n,...s}=e;return s}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Mt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let k;const Dt=new Uint8Array(16);function Gt(){if(!k){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");k=crypto.getRandomValues.bind(crypto)}return k(Dt)}const Ut=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),U={randomUUID:Ut};function ct(t,e,n){if(U.randomUUID&&!t)return U.randomUUID();t=t||{};const s=t.random??t.rng?.()??Gt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Mt(s)}const b="__gemini_function_call_thought_signatures__",Lt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Pt=t=>t();function jt(t){const e=t._getType();return wt.isInstance(t)?t.role:e==="tool"?e:t.name??e}function Ft(t){switch(t){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: ${t}`)}}function Kt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Ht(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function $t(t){return{providerName:"Google Gemini",fromStandardTextBlock(n){return{text:n.text}},fromStandardImageBlock(n){if(!t)throw new Error("This model does not support images");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.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(!t)throw new Error("This model does not support audio");if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.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(!t)throw new Error("This model does not support files");if(n.source_type==="text")return{text:n.text};if(n.source_type==="url"){const s=x({dataUrl:n.url});return s?{inlineData:{mimeType:s.mime_type,data:s.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(t,e){if(Rt(t))return At(t,$t(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return Kt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function Yt(t,e,n,s){if(St(t)){const u=t.name??Ht(t,n);if(u===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 "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const c=Array.isArray(t.content)?t.content.map(p=>L(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:c}}}}]:[{functionResponse:{name:u,response:{result:c}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>L(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[b];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const c=Pt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?Lt:""});return{functionCall:{name:u.name,args:u.args},...c?{thoughtSignature:c}:{}}})),[...o,...i]}function P(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!vt(o))throw new Error("Unsupported message input");const u=jt(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const c=Ft(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Yt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const d=i.content[i.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:i.content}}let l=c;(l==="function"||l==="system"&&!n)&&(l="user");const f={role:l,parts:r};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function Bt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);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=[];const u=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(l=>"text"in l)?.text??c),{generations:[{text:c,message:new _t({content:a??"",tool_calls:o?.map(r=>({type:"tool_call",id:r.id,name:r.functionCall.name,args:r.functionCall.args})),additional_kwargs:{...i,[b]:u},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function qt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts.reduce((r,l)=>("functionCall"in l&&l.functionCall&&r.push({...l,id:"id"in l.functionCall&&typeof l.functionCall.id=="string"?l.functionCall.id:ct()}),r),[]);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 u="";a&&typeof a=="string"?u=a:Array.isArray(a)&&(u=a.find(l=>"text"in l)?.text??"");const c=[];o&&c.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const p=o?.reduce((r,l)=>("thoughtSignature"in l&&typeof l.thoughtSignature=="string"&&(r[l.id]=l.thoughtSignature),r),{});return new Et({text:u,message:new Tt({content:a||"",name:s?s.role:void 0,tool_call_chunks:c,additional_kwargs:{[b]:p},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Wt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:{name:e.name,description:e.description,parameters:n}}return rt(e)?{name:e.function.name,description:e.function.description??"A function available to call.",parameters:bt(e.function.parameters)}:e})}]}function j(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends mt{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await xt(this.zodSchema,t);if(e.success)return e.data;throw new Ct(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(i=>{const{message:o}=i;return!("tool_calls"in o)||!Array.isArray(o.tool_calls)?[]:o.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},K;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(K||(K={}));var H;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(H||(H={}));var $;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})($||($={}));const Y=["user","model","function","system"];var B;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(B||(B={}));var q;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(q||(q={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var V;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(V||(V={}));var T;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(T||(T={}));var J;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(J||(J={}));var E;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(E||(E={}));var z;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(z||(z={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class dt extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class ft extends m{}const Vt="https://generativelanguage.googleapis.com",Jt="v1beta",zt="0.24.1",Zt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class Qt{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Jt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||Vt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function Xt(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Zt}/${zt}`),e.join(" ")}async function te(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",Xt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function ee(t,e,n,s,i,o){const a=new Qt(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},oe(o)),{method:"POST",headers:await te(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:c}=await ee(t,e,n,s,i,o);return ne(u,c,a)}async function ne(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){se(i,t)}return s.ok||await ie(s,t),s}function se(t,e){let n=t;throw n.name==="AbortError"?(n=new ft(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof dt||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ie(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new dt(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function oe(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function M(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return ae(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),A(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ae(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
|
|
2
2
|
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&o.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Z(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.functionCall&&o.push(a.functionCall);if(o.length>0)return o}const re=[T.RECITATION,T.SAFETY,T.LANGUAGE];function A(t){return!!t.finishReason&&re.includes(t.finishReason)}function O(t){var e,n,s;let i="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)i+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(i+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(i+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((s=t.candidates)===null||s===void 0)&&s[0]){const o=t.candidates[0];A(o)&&(i+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(i+=`: ${o.finishMessage}`))}return i}function w(t){return this instanceof w?(this.v=t,this):new w(t)}function ue(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=n.apply(t,e||[]),i,o=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(f){s[f]&&(i[f]=function(d){return new Promise(function(g,C){o.push([f,d,g,C])>1||u(f,d)})})}function u(f,d){try{c(s[f](d))}catch(g){l(o[0][3],g)}}function c(f){f.value instanceof w?Promise.resolve(f.value.v).then(p,r):l(o[0][2],f)}function p(f){u("next",f)}function r(f){u("throw",f)}function l(f,d){f(d),o.shift(),o.length&&u(o[0][0],o[0][1])}}const Q=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function le(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=fe(e),[s,i]=n.tee();return{stream:de(s),response:ce(i)}}async function ce(t){const e=[],n=t.getReader();for(;;){const{done:s,value:i}=await n.read();if(s)return M(pe(e));e.push(i)}}function de(t){return ue(this,arguments,function*(){const n=t.getReader();for(;;){const{value:s,done:i}=yield w(n.read());if(i)break;yield yield w(M(s))}})}function fe(t){const e=t.getReader();return new ReadableStream({start(s){let i="";return o();function o(){return e.read().then(({value:a,done:u})=>{if(u){if(i.trim()){s.error(new m("Failed to parse stream"));return}s.close();return}i+=a;let c=i.match(Q),p;for(;c;){try{p=JSON.parse(c[1])}catch{s.error(new m(`Error parsing JSON response: "${c[1]}"`));return}s.enqueue(p),i=i.substring(c[0].length),c=i.match(Q)}return o()}).catch(a=>{let u=a;throw u.stack=a.stack,u.name==="AbortError"?u=new ft("Request aborted when reading from the stream"):u=new m("Error reading from the stream"),u})}}})}function pe(t){const e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(const s of t){if(s.candidates){let i=0;for(const o of s.candidates)if(n.candidates||(n.candidates=[]),n.candidates[i]||(n.candidates[i]={index:i}),n.candidates[i].citationMetadata=o.citationMetadata,n.candidates[i].groundingMetadata=o.groundingMetadata,n.candidates[i].finishReason=o.finishReason,n.candidates[i].finishMessage=o.finishMessage,n.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){n.candidates[i].content||(n.candidates[i].content={role:o.content.role||"user",parts:[]});const a={};for(const u of o.content.parts)u.text&&(a.text=u.text),u.functionCall&&(a.functionCall=u.functionCall),u.executableCode&&(a.executableCode=u.executableCode),u.codeExecutionResult&&(a.codeExecutionResult=u.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),n.candidates[i].content.parts.push(a)}i++}s.usageMetadata&&(n.usageMetadata=s.usageMetadata)}return n}async function pt(t,e,n,s){const i=await R(e,v.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s);return le(i)}async function gt(t,e,n,s){const o=await(await R(e,v.GENERATE_CONTENT,t,!1,JSON.stringify(n),s)).json();return{response:M(o)}}function ht(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function S(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return ge(e)}function ge(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,i=!1;for(const o of t)"functionResponse"in o?(n.parts.push(o),i=!0):(e.parts.push(o),s=!0);if(s&&i)throw new m("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!s&&!i)throw new m("No content is provided for sending chat message.");return s?e:n}function he(t,e){var n;let s={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const i=t.generateContentRequest!=null;if(t.contents){if(i)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");s.contents=t.contents}else if(i)s=Object.assign(Object.assign({},s),t.generateContentRequest);else{const o=S(t);s.contents=[o]}return{generateContentRequest:s}}function X(t){let e;return t.contents?e=t:e={contents:[S(t)]},t.systemInstruction&&(e.systemInstruction=ht(t.systemInstruction)),e}function me(t){return typeof t=="string"||Array.isArray(t)?{content:S(t)}:t}const tt=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],Ce={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function Oe(t){let e=!1;for(const n of t){const{role:s,parts:i}=n;if(!e&&s!=="user")throw new m(`First content should be with role 'user', got ${s}`);if(!Y.includes(s))throw new m(`Each item should include role field. Got ${s} but valid roles are: ${JSON.stringify(Y)}`);if(!Array.isArray(i))throw new m("Content should have 'parts' property with an array of Parts");if(i.length===0)throw new m("Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const u of i)for(const c of tt)c in u&&(o[c]+=1);const a=Ce[s];for(const u of tt)if(!a.includes(u)&&o[u]>0)throw new m(`Content with role '${s}' can't contain '${u}' part`);e=!0}}function et(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const s of n.parts)if(s===void 0||Object.keys(s).length===0||s.text!==void 0&&s.text==="")return!1;return!0}const nt="SILENT_ERROR";class ye{constructor(e,n,s,i={}){this.model=n,this.params=s,this._requestOptions=i,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,s?.history&&(Oe(s.history),this._history=s.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n);let f;return this._sendPromise=this._sendPromise.then(()=>gt(this._apiKey,this.model,r,l)).then(d=>{var g;if(et(d.response)){this._history.push(p);const C=Object.assign({parts:[],role:"model"},(g=d.response.candidates)===null||g===void 0?void 0:g[0].content);this._history.push(C)}else{const C=O(d.response);C&&console.warn(`sendMessage() was unsuccessful. ${C}. Inspect response object for details.`)}f=d}).catch(d=>{throw this._sendPromise=Promise.resolve(),d}),await this._sendPromise,f}async sendMessageStream(e,n={}){var s,i,o,a,u,c;await this._sendPromise;const p=S(e),r={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,p]},l=Object.assign(Object.assign({},this._requestOptions),n),f=pt(this._apiKey,this.model,r,l);return this._sendPromise=this._sendPromise.then(()=>f).catch(d=>{throw new Error(nt)}).then(d=>d.response).then(d=>{if(et(d)){this._history.push(p);const g=Object.assign({},d.candidates[0].content);g.role||(g.role="model"),this._history.push(g)}else{const g=O(d);g&&console.warn(`sendMessageStream() was unsuccessful. ${g}. Inspect response object for details.`)}}).catch(d=>{d.message!==nt&&console.error(d)}),f}}async function Ie(t,e,n,s){return(await R(e,v.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}async function ve(t,e,n,s){return(await R(e,v.EMBED_CONTENT,t,!1,JSON.stringify(n),s)).json()}async function _e(t,e,n,s){const i=n.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await R(e,v.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:i}),s)).json()}class st{constructor(e,n,s={}){this.apiKey=e,this._requestOptions=s,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=ht(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return gt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}async generateContentStream(e,n={}){var s;const i=X(e),o=Object.assign(Object.assign({},this._requestOptions),n);return pt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}startChat(e){var n;return new ye(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},e),this._requestOptions)}async countTokens(e,n={}){const s=he(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),i=Object.assign(Object.assign({},this._requestOptions),n);return Ie(this.apiKey,this.model,s,i)}async embedContent(e,n={}){const s=me(e),i=Object.assign(Object.assign({},this._requestOptions),n);return ve(this.apiKey,this.model,s,i)}async batchEmbedContents(e,n={}){const s=Object.assign(Object.assign({},this._requestOptions),n);return _e(this.apiKey,this.model,e,s)}}class it{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new m("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new st(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,s){if(!e.name)throw new y("Cached content must contain a `name` field.");if(!e.model)throw new y("Cached content must contain a `model` field.");const i=["model","systemInstruction"];for(const a of i)if(n?.[a]&&e[a]&&n?.[a]!==e[a]){if(a==="model"){const u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(u===c)continue}throw new y(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${e[a]})`)}const o=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new st(this.apiKey,o,s)}}function ot(t,e){const n=Ee(t),s=we(n,e);return{tools:n,toolConfig:s}}function Ee(t){let e=[];const n=[];return t.forEach(i=>{if(at(i)){const[o]=Wt([i]);o.functionDeclarations&&e.push(...o.functionDeclarations)}else if(rt(i)){const{functionDeclarations:o}=Te(i);if(o)e.push(...o);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(i)}),n.find(i=>"functionDeclarations"in i)?n.map(i=>{if(e?.length>0&&"functionDeclarations"in i){const o={functionDeclarations:[...i.functionDeclarations||[],...e]};return e=[],o}return i}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function Te(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:I(t.function.parameters)}]}}function we(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:s}=e,i={any:E.ANY,auto:E.AUTO,none:E.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:i[n]??"MODE_UNSPECIFIED",allowedFunctionNames:s}};if(typeof n=="string"||s)return{functionCallingConfig:{mode:E.ANY,allowedFunctionNames:[...s??[],...n&&typeof n=="string"?[n]:[]]}}}const Se={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}};var Re=Se,Me=class extends Ot{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;thinkingConfig;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")||this.model.startsWith("gemini-3")}constructor(t){if(super(t),this.model=t.model.replace(/^models\//,""),this.maxOutputTokens=t.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=t.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=t.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=t.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=t.stopSequences??this.stopSequences,this.apiKey=t.apiKey??kt("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=t.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=t.streaming??this.streaming,this.json=t.json,this.thinkingConfig=t.thinkingConfig??this.thinkingConfig,this.client=new it(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"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:t.apiVersion,baseUrl:t.baseUrl}),this.streamUsage=t.streamUsage??this.streamUsage}useCachedContent(t,e,n){this.apiKey&&(this.client=new it(this.apiKey).getGenerativeModelFromCachedContent(t,e,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(t){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:t.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(t,e){return this.withConfig({tools:ot(t)?.tools,...e})}invocationParams(t){const e=t?.tools?.length?ot(t.tools,{toolChoice:t.tool_choice,allowedFunctionNames:t.allowedFunctionNames}):void 0;return t?.responseSchema?(this.client.generationConfig.responseSchema=t.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...e?.tools?{tools:e.tools}:{},...e?.toolConfig?{toolConfig:e.toolConfig}:{}}}async _generate(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[p]=s;this.client.systemInstruction=p,i=s.slice(1)}const o=this.invocationParams(e);if(this.streaming){const p={},r=this._streamResponseChunks(t,e,n),l={};for await(const d of r){const g=d.generationInfo?.completion??0;l[g]===void 0?l[g]=d:l[g]=l[g].concat(d)}return{generations:Object.entries(l).sort(([d],[g])=>parseInt(d,10)-parseInt(g,10)).map(([d,g])=>g),llmOutput:{estimatedTokenUsage:p}}}const a=await this.completionWithRetry({...o,contents:i});let u;"usageMetadata"in a.response&&(u=j(a.response.usageMetadata,this.model));const c=Bt(a.response,{usageMetadata:u});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??""),c}async*_streamResponseChunks(t,e,n){const s=P(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[f]=s;this.client.systemInstruction=f,i=s.slice(1)}const a={...this.invocationParams(e),contents:i},u=await this.caller.callWithOptions({signal:e?.signal},async()=>{const{stream:f}=await this.client.generateContentStream(a);return f});let c,p=0,r=0,l=0;for await(const f of u){if("usageMetadata"in f&&f.usageMetadata!==void 0&&this.streamUsage!==!1&&e.streamUsage!==!1){c=j(f.usageMetadata,this.model);const g=f.usageMetadata.promptTokenCount??0;c.input_tokens=Math.max(0,g-p),p=g;const C=f.usageMetadata.candidatesTokenCount??0;c.output_tokens=Math.max(0,C-r),r=C;const D=f.usageMetadata.totalTokenCount??0;c.total_tokens=Math.max(0,D-l),l=D}const d=qt(f,{usageMetadata:c});d&&(yield d,await n?.handleLLMNewToken(d.text??""))}}async completionWithRetry(t,e){return this.caller.callWithOptions({signal:e?.signal},async()=>{try{return await this.client.generateContent(t)}catch(n){throw n.message?.includes("400 Bad Request")&&(n.status=400),n}})}get profile(){return Re[this.model]??{}}withStructuredOutput(t,e){const n=t,s=e?.name,i=e?.method,o=e?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,u;if(i==="functionCalling"){let l=s??"extract",f;if(ut(n)){const d=N(n);f=[{functionDeclarations:[{name:l,description:d.description??"A function available to call.",parameters:d}]}],u=new F({returnSingle:!0,keyName:l,zodSchema:n})}else{let d;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(d=n,d.parameters=I(n.parameters),l=n.name):d={name:l,description:n.description??"",parameters:I(n)},f=[{functionDeclarations:[d]}],u=new F({returnSingle:!0,keyName:l})}a=this.bindTools(f).withConfig({allowedFunctionNames:[l]})}else{const l=N(n);a=this.withConfig({responseSchema:l}),u=new yt}if(!o)return a.pipe(u).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const c=G.assign({parsed:(l,f)=>u.invoke(l.raw,f)}),p=G.assign({parsed:()=>null}),r=c.withFallbacks({fallbacks:[p]});return Nt.from([{raw:a},r]).withConfig({runName:"StructuredOutputRunnable"})}};export{Me as ChatGoogleGenerativeAI};
|