@mcp-use/inspector 2.1.0-canary.3 → 2.1.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/cdn/inspector.js +5 -5
- package/dist/client/index.js +31 -31
- package/dist/web/assets/{browser-Do8zBOpN.js → browser-B9-ahWW6.js} +12 -12
- package/dist/web/assets/{chunk-M5NJO4WR-Do7L5RDx.js → chunk-FDNVT4RA-C4amwMhu.js} +1 -1
- package/dist/web/assets/{chunk-LG5NSHEL-dE03JHzi.js → chunk-LG5NSHEL-nPdzzOXc.js} +1 -1
- package/dist/web/assets/{chunk-QNXTFODW-C7Yf0TjD.js → chunk-WRL45O5E-C7sNvNRg.js} +1 -1
- package/dist/web/assets/{chunk_array-CZ9Igu7C.js → chunk_array-Bw1lTtex.js} +1 -1
- package/dist/web/assets/{client-HCzjEcf6.js → client-BeIkq9vO.js} +1 -1
- package/dist/web/assets/{client-LWDVEFBW-BaSj9Sdi.js → client-W7K33MEL-CSZOULYm.js} +3 -3
- package/dist/web/assets/{dist-CwVubZgG.js → dist-BZmXa__p.js} +1 -1
- package/dist/web/assets/{dist-BaO3qHVt.js → dist-JsQmV3pO.js} +1 -1
- package/dist/web/assets/{dist-8DnA4W8u.js → dist-t5Yo0YiG.js} +1 -1
- package/dist/web/assets/{function_calling-l_oTDrug.js → function_calling-kK7um7Ye.js} +1 -1
- package/dist/web/assets/{index-CLu_NBFk.js → index-hXPV2uCR.js} +8 -8
- package/dist/web/assets/{llms-9ZdWocdy.js → llms-ByyTYk2T.js} +1 -1
- package/dist/web/assets/{messages-DyY5uvh8.js → messages-D4_mH1tk.js} +1 -1
- package/dist/web/assets/react-CgQlyaZ6.js +1 -0
- package/dist/web/assets/{stdio-I25TKTWI-B9cT_Wm7.js → stdio-MZVPQHDD-DJ3TKub-.js} +1 -1
- package/dist/web/assets/{tools-BYpLdT-O.js → tools-kLe9X8V8.js} +1 -1
- package/dist/web/index.html +6 -6
- package/package.json +3 -3
- package/dist/web/assets/react-DRHFd_Ag.js +0 -1
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-BF5JV8uu.js","assets/chunk-QWQYAQCK-BR4V0xsV.js","assets/chunk-3GQAWCBQ-ntjTDD_C.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-B14ZPq5a.js","assets/preload-helper-ckxxtgMM.js","assets/client-
|
|
2
|
-
import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{n as t}from"./chunk-QWQYAQCK-BR4V0xsV.js";import{$n as n,A as r,An as i,At as a,Bt as o,Cn as s,Ct as c,D as l,Dn as u,Dt as d,En as f,Et as p,F as m,Gn as h,Gt as g,H as _,Hn as v,Ht as y,I as b,It as x,Jn as S,Kn as ee,Lt as te,Mt as ne,N as re,Nt as ie,O as ae,On as oe,Ot as se,P as ce,Pt as le,Qn as ue,Rt as de,S as fe,Sn as pe,St as me,Tn as he,Tt as ge,U as _e,Un as ve,Vn as ye,Vt as be,Wn as xe,Wt as Se,Xn as C,Xt as w,Yn as Ce,Zn as T,Zt as we,_n as Te,_t as Ee,a as E,b as De,bn as Oe,bt as ke,cn as D,ct as Ae,dn as O,dt as je,er as k,et as Me,fn as Ne,ft as Pe,gn as A,gt as Fe,i as Ie,it as Le,j as Re,jn as ze,jt as Be,k as Ve,kn as He,kt as Ue,l as We,ln as Ge,lt as Ke,m as qe,mn as Je,mt as Ye,n as Xe,nn as Ze,on as Qe,qn as $e,qt as et,r as tt,rt as nt,s as rt,sn as it,st as at,tn as ot,tr as st,tt as ct,un as lt,v as ut,vt as dt,w as ft,wn as pt,wt as mt,x as ht,xn as gt,xt as _t,y as vt,yn as yt,yt as bt,zn as j,zt as xt}from"./messages-DyY5uvh8.js";import{It as St,S as Ct,er as wt}from"./json-schema-processors-DNSjFPrk.js";import{a as Tt,c as Et,s as Dt}from"./client-HCzjEcf6.js";import{a as Ot,c as kt,m as M,n as At,v as jt}from"./schemas-BrqAD_Qo.js";import"./chunk-QNXTFODW-C7Yf0TjD.js";import{t as Mt}from"./preload-helper-ckxxtgMM.js";import"./chunk-M5NJO4WR-Do7L5RDx.js";import{C as Nt,D as Pt,M as Ft,O as It,S as Lt,T as Rt,_ as zt,b as Bt,c as Vt,d as Ht,f as Ut,g as Wt,h as Gt,j as Kt,k as qt,m as Jt,n as Yt,s as Xt,u as Zt,v as Qt,x as $t,y as en}from"./function_calling-l_oTDrug.js";import{a as tn,i as nn,n as rn,o as an,r as on,t as sn}from"./tools-BYpLdT-O.js";import{n as cn,r as ln,t as un}from"./chunk_array-CZ9Igu7C.js";import{n as dn,r as fn,t as pn}from"./llms-9ZdWocdy.js";import{t as mn}from"./chunk-LG5NSHEL-dE03JHzi.js";import"./chunk-UJPHRNQP-B14ZPq5a.js";var hn,gn,_n=0,vn=0;function yn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=hn,o??=gn),a==null||o==null){var s=e.random||(e.rng||de)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!hn&&!e._v6&&(a[0]|=1,hn=a)),o??(o=(s[6]<<8|s[7])&16383,gn===void 0&&!e._v6&&(gn=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?vn+1:e.nsecs,u=c-_n+(l-vn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>_n)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);_n=c,vn=l,gn=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||xt(i)}function bn(e){var t=xn(typeof e==`string`?o(e):e);return typeof e==`string`?xt(t):t}function xn(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Sn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Cn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Sn(Object(n),!0).forEach(function(t){wn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function wn(e,t,n){return(t=Tn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tn(e){var t=En(e,`string`);return typeof t==`symbol`?t:t+``}function En(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Dn(e={},t,n=0){var r=yn(Cn(Cn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=bn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return xt(r)}var On=Object.defineProperty,kn=(e,t)=>{for(var n in t)On(e,n,{get:t[n],enumerable:!0})};kn({},{ConfigurableModel:()=>Fn,MODEL_PROVIDER_CONFIG:()=>An,_inferModelProvider:()=>Pn,getChatModelByClassName:()=>Mn,initChatModel:()=>In});var An={openai:{package:`@langchain/openai`,className:`ChatOpenAI`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`},azure_openai:{package:`@langchain/openai`,className:`AzureChatOpenAI`},cohere:{package:`@langchain/cohere`,className:`ChatCohere`},"google-vertexai":{package:`@langchain/google-vertexai`,className:`ChatVertexAI`},"google-vertexai-web":{package:`@langchain/google-vertexai-web`,className:`ChatVertexAI`},"google-genai":{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`},ollama:{package:`@langchain/ollama`,className:`ChatOllama`},mistralai:{package:`@langchain/mistralai`,className:`ChatMistralAI`},mistral:{package:`@langchain/mistralai`,className:`ChatMistralAI`},groq:{package:`@langchain/groq`,className:`ChatGroq`},cerebras:{package:`@langchain/cerebras`,className:`ChatCerebras`},bedrock:{package:`@langchain/aws`,className:`ChatBedrockConverse`},deepseek:{package:`@langchain/deepseek`,className:`ChatDeepSeek`},xai:{package:`@langchain/xai`,className:`ChatXAI`},fireworks:{package:`@langchain/community/chat_models/fireworks`,className:`ChatFireworks`,hasCircularDependency:!0},together:{package:`@langchain/community/chat_models/togetherai`,className:`ChatTogetherAI`,hasCircularDependency:!0},perplexity:{package:`@langchain/community/chat_models/perplexity`,className:`ChatPerplexity`,hasCircularDependency:!0}},jn=Object.keys(An);async function Mn(e){let t=Object.entries(An).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await Mt(()=>import(n.package),[]))[n.className]}catch(e){let t=e;if(`code`in t&&t.code?.toString().includes(`ERR_MODULE_NOT_FOUND`)&&`message`in t&&typeof t.message==`string`){let e=(t.message.startsWith(`Error: `)?t.message.slice(7):t.message).split(`Cannot find package '`)[1].split(`'`)[0];throw Error(`Unable to import ${e}. Please install with \`npm install ${e}\` or \`pnpm install ${e}\``)}throw e}}async function Nn(e,t,n={}){let r=t||Pn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=An[r];if(!i){let e=jn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Mn(i.className)))({model:e,...o})}function Pn(e){if(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)||e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`))return`openai`;if(e.startsWith(`claude`))return`anthropic`;if(e.startsWith(`command`))return`cohere`;if(e.startsWith(`accounts/fireworks`))return`fireworks`;if(e.startsWith(`gemini`))return`google-vertexai`;if(e.startsWith(`amazon.`))return`bedrock`;if(e.startsWith(`mistral`))return`mistralai`;if(e.startsWith(`sonar`)||e.startsWith(`pplx`))return`perplexity`}var Fn=class e extends Xt{_llmType(){return`chat_model`}lc_namespace=[`langchain`,`chat_models`];_defaultConfig={};_configurableFields=`any`;_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields===`any`?this._configurableFields=`any`:this._configurableFields=e.configurableFields??[`model`,`modelProvider`],e.configPrefix?this._configPrefix=e.configPrefix.endsWith(`_`)?e.configPrefix:`${e.configPrefix}_`:this._configPrefix=``,this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){let t=this._getCacheKey(e),n=this._modelInstanceCache.get(t);if(n)return n;let r={...this._defaultConfig,...this._modelParams(e)},i=await Nn(r.model,r.modelProvider,r);for(let[e,t]of Object.entries(this._queuedMethodOperations))e in i&&typeof i[e]==`function`&&(i=await i[e](...t));return this._modelInstanceCache.set(t,i),i}async _generate(e,t,n){return(await this._getModelInstance(t))._generate(e,t??{},n)}bindTools(t,n){let r={...this._queuedMethodOperations};return r.bindTools=[t,n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{let r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){let t=e?.configurable??{},n={};for(let[e,r]of Object.entries(t))if(e.startsWith(this._configPrefix)){let t=this._removePrefix(e,this._configPrefix);n[t]=r}return this._configurableFields!==`any`&&(n=Object.fromEntries(Object.entries(n).filter(([e])=>this._configurableFields.includes(e)))),n}_removePrefix(e,t){return e.startsWith(t)?e.slice(t.length):e}withConfig(t){let n={...t||{}},r=this._modelParams(n),i=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`configurable`));return i.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([e])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(e,this._configPrefix)))),new rt({config:n,bound:new e({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,t){let n=await this._getModelInstance(t),r=Ee(t);return n.invoke(e,r)}async stream(e,t){let n=new je({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,Pe.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=Ee(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=Ee(t);yield*r.streamLog(e,i,{...n,_schemaFormat:`original`,includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,t,n){let r=this;async function*i(){let i=await r._getModelInstance(t),a=Ee(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return Pe.fromAsyncGenerator(i())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let t=e??{};if(t.configurable){let{configurable:e}=t,n={};for(let[t,r]of Object.entries(e))t.startsWith(`__pregel_`)||(n[t]=r);t={...t,configurable:n}}return JSON.stringify(t)}};async function In(e,t){let{configurableFields:n,configPrefix:r,modelProvider:i,profile:a,...o}={configPrefix:``,...t??{}};if(i===void 0&&e?.includes(`:`)){let[t,...n]=e.split(`:`),r=n.length===0?[t]:[t,n.join(`:`)];jn.includes(r[0])&&([i,e]=r)}let s=Array.isArray(n)?[...n]:n;!e&&s===void 0&&(s=[`model`,`modelProvider`]),r&&s===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let c={...o},l;return s===void 0?l=new Fn({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new Fn({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Ln=class{constructor(){this.store=void 0}getStore(){return this.store}run(e,t,...n){this.store=e;try{return t(...n)}finally{this.store=void 0}}exit(e,...t){let n=this.store;this.store=void 0;try{return e(...t)}finally{this.store=n}}enterWith(e){this.store=e}disable(){this.store=void 0}};function Rn(){c.initializeGlobalInstance(new Ln)}var zn=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Bn=class extends zn{get is_bubble_up(){return!0}},Vn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Hn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Un=class extends Bn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Wn=class extends Un{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Gn=class extends Bn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function Kn(e){return e!==void 0&&e.name===Gn.unminifiable_name}function qn(e){return e!==void 0&&e.is_bubble_up===!0}function Jn(e){return e!==void 0&&[Un.unminifiable_name,Wn.unminifiable_name].includes(e.name)}var Yn=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},N=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},P=class extends zn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Xn=class extends zn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Zn=class extends zn{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}};function Qn(e){return Dn({clockseq:e})}function $n(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return x(e,new Uint8Array(n))}var er=`__error__`,tr=`__scheduled__`,nr=`__interrupt__`,rr=`__resume__`,ir=`[...]`,ar=`[Circular]`,or=[],sr=[];function cr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function lr(e,t,n,r){r===void 0&&(r=cr()),dr(e,``,0,[],void 0,0,r);var i;try{i=sr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,fr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;or.length!==0;){var a=or.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function ur(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,or.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),or.push([r,n,t,i])):sr.push([t,n,e])}function dr(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){ur(ar,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){ur(ir,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){ur(ir,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)dr(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];dr(e[l],l,s,r,e,a,o)}}r.pop()}}function fr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(sr.length>0)for(var r=0;r<sr.length;r++){var i=sr[r];if(i[1]===t&&i[0]===n){n=i[2],sr.splice(r,1);break}}return e.call(this,t,n)}}var pr=[],mr={},hr={};j(hr,{BaseChatMessageHistory:()=>gr,BaseListChatMessageHistory:()=>_r,InMemoryChatMessageHistory:()=>vr});var gr=class extends he{async addMessages(e){for(let t of e)await this.addMessage(t)}},_r=class extends he{addUserMessage(e){return this.addMessage(new O(e))}addAIMessage(e){return this.addMessage(new w(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},vr=class extends _r{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},yr={},br={};j(br,{BaseMemory:()=>xr,getInputValue:()=>Cr,getOutputValue:()=>wr,getPromptInputKey:()=>Tr});var xr=class{},Sr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},Cr=(e,t)=>{let n=Sr(e,t);if(!n)throw Error(`input values have ${Object.keys(e).length} keys, you must specify an input key or pass only 1 key as input`);return n},wr=(e,t)=>{let n=Sr(e,t);if(!n&&n!==``)throw Error(`output values have ${Object.keys(e).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Tr(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Er={};j(Er,{BaseStore:()=>Dr,InMemoryStore:()=>Or});var Dr=class extends he{},Or=class extends Dr{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},kr={};j(kr,{BaseRetriever:()=>Ar});var Ar=class extends E{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=Ee(p(t)),r=await(await mt.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},jr={};j(jr,{SaveableVectorStore:()=>Pr,VectorStore:()=>Nr,VectorStoreRetriever:()=>Mr});var Mr=class extends Ar{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Nr=class extends he{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Mr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Mr({...t,searchKwargs:e.searchKwargs}):new Mr({...t})}}},Pr=class extends Nr{static load(e,t){throw Error(`Not implemented`)}},Fr={};j(Fr,{BaseDocumentLoader:()=>Ir});var Ir=class{},Lr={};j(Lr,{LangSmithLoader:()=>Rr});var Rr=class extends Ir{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new ne(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??zr,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function zr(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Br=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Vr=class extends E{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Hr=class extends Vr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Ur={};j(Ur,{BaseDocumentTransformer:()=>Vr,Document:()=>Br,MappingDocumentTransformer:()=>Hr});var Wr=class extends he{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Gr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},Kr=class extends Gr{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function qr(e){return e._modelType()===`base_llm`}function Jr(e){return e._modelType()===`base_chat_model`}function Yr(e){return e.split(/\n| /).length}var Xr=class e extends Wr{examples=[];examplePrompt;getTextLength=Yr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Yr}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function Zr(e){return Object.keys(e).sort().map(t=>e[t])}var Qr=class e extends Wr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=Zr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Br({pageContent:t,metadata:e})])}async selectExamples(e){let t=Zr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>Zr(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},$r={};j($r,{BaseExampleSelector:()=>Wr,BasePromptSelector:()=>Gr,ConditionalPromptSelector:()=>Kr,LengthBasedExampleSelector:()=>Xr,SemanticSimilarityExampleSelector:()=>Qr,isChatModel:()=>Jr,isLLM:()=>qr});var ei=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ti=class extends he{lc_namespace=[`langchain`,`recordmanagers`]},ni=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=zt;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new Br({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return x(this.keyEncoder(e),ei)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return x(this.keyEncoder(t),ei)}};function ri(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ii(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function ai(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var oi=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function si(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=oi(t)?await t.load():t,d=ai(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ri(a??100,u);for(let e of _){let t=ii(e.map(e=>ni.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var ci={};j(ci,{RecordManager:()=>ti,UUIDV5_NAMESPACE:()=>ei,_HashedDocument:()=>ni,_batch:()=>ri,_deduplicateInOrder:()=>ii,_getSourceIdAssigner:()=>ai,_isBaseDocumentLoader:()=>oi,index:()=>si});var li={},ui=class extends It{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},di=class extends Pt{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new ui(e)}_diff(e,t){if(t)return Ke(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?ot(r.arguments):{...r,arguments:ot(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},fi=class extends It{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new di;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},pi={};j(pi,{JsonKeyOutputFunctionsParser:()=>fi,JsonOutputFunctionsParser:()=>di,OutputFunctionsParser:()=>ui});var mi=class extends E{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},hi=class extends mi{async formatPromptValue(e){return new Bt(await this.format(e))}},gi=Object.prototype.toString,_i=Array.isArray||function(e){return gi.call(e)===`[object Array]`};function vi(e){return typeof e==`function`}function yi(e){return _i(e)?`array`:typeof e}function bi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function xi(e,t){return typeof e==`object`&&!!e&&t in e}function Si(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ci=RegExp.prototype.test;function wi(e,t){return Ci.call(e,t)}var Ti=/\S/;function Ei(e){return!wi(Ti,e)}var Di={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`,"`":```,"=":`=`};function Oi(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Di[e]})}var ki=/\s*/,Ai=/\s+/,ji=/\s*=/,Mi=/\s*\}/,Ni=/#|\^|\/|>|\{|&|=|!/;function Pi(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(Ai,2)),!_i(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(bi(e[0])+`\\s*`),f=RegExp(`\\s*`+bi(e[1])),p=RegExp(`\\s*`+bi(`}`+e[1]))}m(t||I.tags);for(var h=new Li(e),g,_,v,y,b,x;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var S=0,ee=v.length;S<ee;++S)y=v.charAt(S),Ei(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-BF5JV8uu.js","assets/chunk-QWQYAQCK-BR4V0xsV.js","assets/chunk-3GQAWCBQ-ntjTDD_C.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-B14ZPq5a.js","assets/preload-helper-ckxxtgMM.js","assets/client-W7K33MEL-CSZOULYm.js","assets/client-BeIkq9vO.js","assets/schemas-BrqAD_Qo.js","assets/json-schema-processors-DNSjFPrk.js","assets/chunk-WRL45O5E-C7sNvNRg.js","assets/path-CG3438uq.js","assets/chunk-LG5NSHEL-nPdzzOXc.js","assets/display-A5IEINAP-B8BJrcag.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{n as t}from"./chunk-QWQYAQCK-BR4V0xsV.js";import{$n as n,A as r,An as i,At as a,Bt as o,Cn as s,Ct as c,D as l,Dn as u,Dt as d,En as f,Et as p,F as m,Gn as h,Gt as g,H as _,Hn as v,Ht as y,I as b,It as x,Jn as S,Kn as ee,Lt as te,Mt as ne,N as re,Nt as ie,O as ae,On as oe,Ot as se,P as ce,Pt as le,Qn as ue,Rt as de,S as fe,Sn as pe,St as me,Tn as he,Tt as ge,U as _e,Un as ve,Vn as ye,Vt as be,Wn as xe,Wt as Se,Xn as C,Xt as w,Yn as Ce,Zn as T,Zt as we,_n as Te,_t as Ee,a as E,b as De,bn as Oe,bt as ke,cn as D,ct as Ae,dn as O,dt as je,er as k,et as Me,fn as Ne,ft as Pe,gn as A,gt as Fe,i as Ie,it as Le,j as Re,jn as ze,jt as Be,k as Ve,kn as He,kt as Ue,l as We,ln as Ge,lt as Ke,m as qe,mn as Je,mt as Ye,nn as Xe,on as Ze,qn as Qe,qt as $e,r as et,rt as tt,s as nt,sn as rt,st as it,t as at,tn as ot,tr as st,tt as ct,un as lt,v as ut,vt as dt,w as ft,wn as pt,wt as mt,x as ht,xn as gt,xt as _t,y as vt,yn as yt,yt as bt,zn as j,zt as xt}from"./messages-D4_mH1tk.js";import{It as St,S as Ct,er as wt}from"./json-schema-processors-DNSjFPrk.js";import{a as Tt,c as Et,s as Dt}from"./client-BeIkq9vO.js";import{a as Ot,c as kt,m as M,n as At,v as jt}from"./schemas-BrqAD_Qo.js";import"./chunk-WRL45O5E-C7sNvNRg.js";import{t as Mt}from"./preload-helper-ckxxtgMM.js";import"./chunk-FDNVT4RA-C4amwMhu.js";import{C as Nt,D as Pt,M as Ft,O as It,S as Lt,T as Rt,_ as zt,b as Bt,c as Vt,d as Ht,f as Ut,g as Wt,h as Gt,j as Kt,k as qt,m as Jt,n as Yt,s as Xt,u as Zt,v as Qt,x as $t,y as en}from"./function_calling-kK7um7Ye.js";import{a as tn,i as nn,n as rn,o as an,r as on,t as sn}from"./tools-kLe9X8V8.js";import{n as cn,r as ln,t as un}from"./chunk_array-Bw1lTtex.js";import{n as dn,r as fn,t as pn}from"./llms-ByyTYk2T.js";import{t as mn}from"./chunk-LG5NSHEL-nPdzzOXc.js";import"./chunk-UJPHRNQP-B14ZPq5a.js";var hn,gn,_n=0,vn=0;function yn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=hn,o??=gn),a==null||o==null){var s=e.random||(e.rng||de)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!hn&&!e._v6&&(a[0]|=1,hn=a)),o??(o=(s[6]<<8|s[7])&16383,gn===void 0&&!e._v6&&(gn=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?vn+1:e.nsecs,u=c-_n+(l-vn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>_n)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);_n=c,vn=l,gn=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||xt(i)}function bn(e){var t=xn(typeof e==`string`?o(e):e);return typeof e==`string`?xt(t):t}function xn(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Sn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Cn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Sn(Object(n),!0).forEach(function(t){wn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function wn(e,t,n){return(t=Tn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tn(e){var t=En(e,`string`);return typeof t==`symbol`?t:t+``}function En(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Dn(e={},t,n=0){var r=yn(Cn(Cn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=bn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return xt(r)}var On=Object.defineProperty,kn=(e,t)=>{for(var n in t)On(e,n,{get:t[n],enumerable:!0})};kn({},{ConfigurableModel:()=>Fn,MODEL_PROVIDER_CONFIG:()=>An,_inferModelProvider:()=>Pn,getChatModelByClassName:()=>Mn,initChatModel:()=>In});var An={openai:{package:`@langchain/openai`,className:`ChatOpenAI`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`},azure_openai:{package:`@langchain/openai`,className:`AzureChatOpenAI`},cohere:{package:`@langchain/cohere`,className:`ChatCohere`},"google-vertexai":{package:`@langchain/google-vertexai`,className:`ChatVertexAI`},"google-vertexai-web":{package:`@langchain/google-vertexai-web`,className:`ChatVertexAI`},"google-genai":{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`},ollama:{package:`@langchain/ollama`,className:`ChatOllama`},mistralai:{package:`@langchain/mistralai`,className:`ChatMistralAI`},mistral:{package:`@langchain/mistralai`,className:`ChatMistralAI`},groq:{package:`@langchain/groq`,className:`ChatGroq`},cerebras:{package:`@langchain/cerebras`,className:`ChatCerebras`},bedrock:{package:`@langchain/aws`,className:`ChatBedrockConverse`},deepseek:{package:`@langchain/deepseek`,className:`ChatDeepSeek`},xai:{package:`@langchain/xai`,className:`ChatXAI`},fireworks:{package:`@langchain/community/chat_models/fireworks`,className:`ChatFireworks`,hasCircularDependency:!0},together:{package:`@langchain/community/chat_models/togetherai`,className:`ChatTogetherAI`,hasCircularDependency:!0},perplexity:{package:`@langchain/community/chat_models/perplexity`,className:`ChatPerplexity`,hasCircularDependency:!0}},jn=Object.keys(An);async function Mn(e){let t=Object.entries(An).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await Mt(()=>import(n.package),[]))[n.className]}catch(e){let t=e;if(`code`in t&&t.code?.toString().includes(`ERR_MODULE_NOT_FOUND`)&&`message`in t&&typeof t.message==`string`){let e=(t.message.startsWith(`Error: `)?t.message.slice(7):t.message).split(`Cannot find package '`)[1].split(`'`)[0];throw Error(`Unable to import ${e}. Please install with \`npm install ${e}\` or \`pnpm install ${e}\``)}throw e}}async function Nn(e,t,n={}){let r=t||Pn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=An[r];if(!i){let e=jn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Mn(i.className)))({model:e,...o})}function Pn(e){if(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)||e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`))return`openai`;if(e.startsWith(`claude`))return`anthropic`;if(e.startsWith(`command`))return`cohere`;if(e.startsWith(`accounts/fireworks`))return`fireworks`;if(e.startsWith(`gemini`))return`google-vertexai`;if(e.startsWith(`amazon.`))return`bedrock`;if(e.startsWith(`mistral`))return`mistralai`;if(e.startsWith(`sonar`)||e.startsWith(`pplx`))return`perplexity`}var Fn=class e extends Xt{_llmType(){return`chat_model`}lc_namespace=[`langchain`,`chat_models`];_defaultConfig={};_configurableFields=`any`;_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields===`any`?this._configurableFields=`any`:this._configurableFields=e.configurableFields??[`model`,`modelProvider`],e.configPrefix?this._configPrefix=e.configPrefix.endsWith(`_`)?e.configPrefix:`${e.configPrefix}_`:this._configPrefix=``,this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){let t=this._getCacheKey(e),n=this._modelInstanceCache.get(t);if(n)return n;let r={...this._defaultConfig,...this._modelParams(e)},i=await Nn(r.model,r.modelProvider,r);for(let[e,t]of Object.entries(this._queuedMethodOperations))e in i&&typeof i[e]==`function`&&(i=await i[e](...t));return this._modelInstanceCache.set(t,i),i}async _generate(e,t,n){return(await this._getModelInstance(t))._generate(e,t??{},n)}bindTools(t,n){let r={...this._queuedMethodOperations};return r.bindTools=[t,n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{let r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){let t=e?.configurable??{},n={};for(let[e,r]of Object.entries(t))if(e.startsWith(this._configPrefix)){let t=this._removePrefix(e,this._configPrefix);n[t]=r}return this._configurableFields!==`any`&&(n=Object.fromEntries(Object.entries(n).filter(([e])=>this._configurableFields.includes(e)))),n}_removePrefix(e,t){return e.startsWith(t)?e.slice(t.length):e}withConfig(t){let n={...t||{}},r=this._modelParams(n),i=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`configurable`));return i.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([e])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(e,this._configPrefix)))),new nt({config:n,bound:new e({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,t){let n=await this._getModelInstance(t),r=Ee(t);return n.invoke(e,r)}async stream(e,t){let n=new je({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,Pe.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=Ee(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=Ee(t);yield*r.streamLog(e,i,{...n,_schemaFormat:`original`,includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,t,n){let r=this;async function*i(){let i=await r._getModelInstance(t),a=Ee(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return Pe.fromAsyncGenerator(i())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let t=e??{};if(t.configurable){let{configurable:e}=t,n={};for(let[t,r]of Object.entries(e))t.startsWith(`__pregel_`)||(n[t]=r);t={...t,configurable:n}}return JSON.stringify(t)}};async function In(e,t){let{configurableFields:n,configPrefix:r,modelProvider:i,profile:a,...o}={configPrefix:``,...t??{}};if(i===void 0&&e?.includes(`:`)){let[t,...n]=e.split(`:`),r=n.length===0?[t]:[t,n.join(`:`)];jn.includes(r[0])&&([i,e]=r)}let s=Array.isArray(n)?[...n]:n;!e&&s===void 0&&(s=[`model`,`modelProvider`]),r&&s===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let c={...o},l;return s===void 0?l=new Fn({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new Fn({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Ln=class{constructor(){this.store=void 0}getStore(){return this.store}run(e,t,...n){this.store=e;try{return t(...n)}finally{this.store=void 0}}exit(e,...t){let n=this.store;this.store=void 0;try{return e(...t)}finally{this.store=n}}enterWith(e){this.store=e}disable(){this.store=void 0}};function Rn(){c.initializeGlobalInstance(new Ln)}var zn=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Bn=class extends zn{get is_bubble_up(){return!0}},Vn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Hn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Un=class extends Bn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Wn=class extends Un{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Gn=class extends Bn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function Kn(e){return e!==void 0&&e.name===Gn.unminifiable_name}function qn(e){return e!==void 0&&e.is_bubble_up===!0}function Jn(e){return e!==void 0&&[Un.unminifiable_name,Wn.unminifiable_name].includes(e.name)}var Yn=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},N=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},P=class extends zn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Xn=class extends zn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Zn=class extends zn{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}};function Qn(e){return Dn({clockseq:e})}function $n(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return x(e,new Uint8Array(n))}var er=`__error__`,tr=`__scheduled__`,nr=`__interrupt__`,rr=`__resume__`,ir=`[...]`,ar=`[Circular]`,or=[],sr=[];function cr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function lr(e,t,n,r){r===void 0&&(r=cr()),dr(e,``,0,[],void 0,0,r);var i;try{i=sr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,fr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;or.length!==0;){var a=or.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function ur(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,or.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),or.push([r,n,t,i])):sr.push([t,n,e])}function dr(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){ur(ar,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){ur(ir,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){ur(ir,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)dr(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];dr(e[l],l,s,r,e,a,o)}}r.pop()}}function fr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(sr.length>0)for(var r=0;r<sr.length;r++){var i=sr[r];if(i[1]===t&&i[0]===n){n=i[2],sr.splice(r,1);break}}return e.call(this,t,n)}}var pr=[],mr={},hr={};j(hr,{BaseChatMessageHistory:()=>gr,BaseListChatMessageHistory:()=>_r,InMemoryChatMessageHistory:()=>vr});var gr=class extends he{async addMessages(e){for(let t of e)await this.addMessage(t)}},_r=class extends he{addUserMessage(e){return this.addMessage(new O(e))}addAIMessage(e){return this.addMessage(new w(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},vr=class extends _r{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},yr={},br={};j(br,{BaseMemory:()=>xr,getInputValue:()=>Cr,getOutputValue:()=>wr,getPromptInputKey:()=>Tr});var xr=class{},Sr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},Cr=(e,t)=>{let n=Sr(e,t);if(!n)throw Error(`input values have ${Object.keys(e).length} keys, you must specify an input key or pass only 1 key as input`);return n},wr=(e,t)=>{let n=Sr(e,t);if(!n&&n!==``)throw Error(`output values have ${Object.keys(e).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Tr(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Er={};j(Er,{BaseStore:()=>Dr,InMemoryStore:()=>Or});var Dr=class extends he{},Or=class extends Dr{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},kr={};j(kr,{BaseRetriever:()=>Ar});var Ar=class extends E{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=Ee(p(t)),r=await(await mt.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},jr={};j(jr,{SaveableVectorStore:()=>Pr,VectorStore:()=>Nr,VectorStoreRetriever:()=>Mr});var Mr=class extends Ar{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Nr=class extends he{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Mr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Mr({...t,searchKwargs:e.searchKwargs}):new Mr({...t})}}},Pr=class extends Nr{static load(e,t){throw Error(`Not implemented`)}},Fr={};j(Fr,{BaseDocumentLoader:()=>Ir});var Ir=class{},Lr={};j(Lr,{LangSmithLoader:()=>Rr});var Rr=class extends Ir{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new ne(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??zr,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function zr(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Br=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Vr=class extends E{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Hr=class extends Vr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Ur={};j(Ur,{BaseDocumentTransformer:()=>Vr,Document:()=>Br,MappingDocumentTransformer:()=>Hr});var Wr=class extends he{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Gr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},Kr=class extends Gr{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function qr(e){return e._modelType()===`base_llm`}function Jr(e){return e._modelType()===`base_chat_model`}function Yr(e){return e.split(/\n| /).length}var Xr=class e extends Wr{examples=[];examplePrompt;getTextLength=Yr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Yr}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function Zr(e){return Object.keys(e).sort().map(t=>e[t])}var Qr=class e extends Wr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=Zr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Br({pageContent:t,metadata:e})])}async selectExamples(e){let t=Zr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>Zr(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},$r={};j($r,{BaseExampleSelector:()=>Wr,BasePromptSelector:()=>Gr,ConditionalPromptSelector:()=>Kr,LengthBasedExampleSelector:()=>Xr,SemanticSimilarityExampleSelector:()=>Qr,isChatModel:()=>Jr,isLLM:()=>qr});var ei=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ti=class extends he{lc_namespace=[`langchain`,`recordmanagers`]},ni=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=zt;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new Br({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return x(this.keyEncoder(e),ei)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return x(this.keyEncoder(t),ei)}};function ri(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ii(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function ai(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var oi=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function si(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=oi(t)?await t.load():t,d=ai(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ri(a??100,u);for(let e of _){let t=ii(e.map(e=>ni.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var ci={};j(ci,{RecordManager:()=>ti,UUIDV5_NAMESPACE:()=>ei,_HashedDocument:()=>ni,_batch:()=>ri,_deduplicateInOrder:()=>ii,_getSourceIdAssigner:()=>ai,_isBaseDocumentLoader:()=>oi,index:()=>si});var li={},ui=class extends It{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},di=class extends Pt{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new ui(e)}_diff(e,t){if(t)return Ke(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?ot(r.arguments):{...r,arguments:ot(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},fi=class extends It{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new di;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},pi={};j(pi,{JsonKeyOutputFunctionsParser:()=>fi,JsonOutputFunctionsParser:()=>di,OutputFunctionsParser:()=>ui});var mi=class extends E{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},hi=class extends mi{async formatPromptValue(e){return new Bt(await this.format(e))}},gi=Object.prototype.toString,_i=Array.isArray||function(e){return gi.call(e)===`[object Array]`};function vi(e){return typeof e==`function`}function yi(e){return _i(e)?`array`:typeof e}function bi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function xi(e,t){return typeof e==`object`&&!!e&&t in e}function Si(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ci=RegExp.prototype.test;function wi(e,t){return Ci.call(e,t)}var Ti=/\S/;function Ei(e){return!wi(Ti,e)}var Di={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`,"`":```,"=":`=`};function Oi(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Di[e]})}var ki=/\s*/,Ai=/\s+/,ji=/\s*=/,Mi=/\s*\}/,Ni=/#|\^|\/|>|\{|&|=|!/;function Pi(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(Ai,2)),!_i(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(bi(e[0])+`\\s*`),f=RegExp(`\\s*`+bi(e[1])),p=RegExp(`\\s*`+bi(`}`+e[1]))}m(t||I.tags);for(var h=new Li(e),g,_,v,y,b,x;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var S=0,ee=v.length;S<ee;++S)y=v.charAt(S),Ei(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
|
|
3
3
|
`&&(u(),c=``,l=0,n=!1);if(!h.scan(d))break;if(o=!0,_=h.scan(Ni)||`name`,h.scan(ki),_===`=`?(v=h.scanUntil(ji),h.scan(ji),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(Mi),h.scanUntil(f),_=`&`):v=h.scanUntil(f),!h.scan(f))throw Error(`Unclosed tag at `+h.pos);if(b=_==`>`?[_,v,g,h.pos,c,l,n]:[_,v,g,h.pos],l++,i.push(b),_===`#`||_===`^`)r.push(b);else if(_===`/`){if(x=r.pop(),!x)throw Error(`Unopened section "`+v+`" at `+g);if(x[1]!==v)throw Error(`Unclosed section "`+x[1]+`" at `+g)}else _===`name`||_===`{`||_===`&`?s=!0:_===`=`&&m(v)}if(u(),x=r.pop(),x)throw Error(`Unclosed section "`+x[1]+`" at `+h.pos);return Ii(Fi(i))}function Fi(e){for(var t=[],n,r,i=0,a=e.length;i<a;++i)n=e[i],n&&(n[0]===`text`&&r&&r[0]===`text`?(r[1]+=n[1],r[3]=n[3]):(t.push(n),r=n));return t}function Ii(e){for(var t=[],n=t,r=[],i,a,o=0,s=e.length;o<s;++o)switch(i=e[o],i[0]){case`#`:case`^`:n.push(i),r.push(i),n=i[4]=[];break;case`/`:a=r.pop(),a[5]=i[2],n=r.length>0?r[r.length-1][4]:t;break;default:n.push(i)}return t}function Li(e){this.string=e,this.tail=e,this.pos=0}Li.prototype.eos=function(){return this.tail===``},Li.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return``;var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n},Li.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail=``;break;case 0:n=``;break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function Ri(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ri.prototype.push=function(e){return new Ri(e,this)},Ri.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var r=this,i,a,o,s=!1;r;){if(e.indexOf(`.`)>0)for(i=r.view,a=e.split(`.`),o=0;i!=null&&o<a.length;)o===a.length-1&&(s=xi(i,a[o])||Si(i,a[o])),i=i[a[o++]];else i=r.view[e],s=xi(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return vi(n)&&(n=n.call(this.view)),n};function F(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}F.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},F.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||I.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=Pi(e,t),i&&n.set(r,a)),a},F.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof Ri?t:new Ri(t,void 0);return this.renderTokens(a,o,n,e,r)},F.prototype.renderTokens=function(e,t,n,r,i){for(var a=``,o,s,c,l=0,u=e.length;l<u;++l)c=void 0,o=e[l],s=o[0],s===`#`?c=this.renderSection(o,t,n,r,i):s===`^`?c=this.renderInverted(o,t,n,r,i):s===`>`?c=this.renderPartial(o,t,n,i):s===`&`?c=this.unescapedValue(o,t):s===`name`?c=this.escapedValue(o,t,i):s===`text`&&(c=this.rawValue(o)),c!==void 0&&(a+=c);return a},F.prototype.renderSection=function(e,t,n,r,i){var a=this,o=``,s=t.lookup(e[1]);function c(e){return a.render(e,t,n,i)}if(s){if(_i(s))for(var l=0,u=s.length;l<u;++l)o+=this.renderTokens(e[4],t.push(s[l]),n,r,i);else if(typeof s==`object`||typeof s==`string`||typeof s==`number`)o+=this.renderTokens(e[4],t.push(s),n,r,i);else if(vi(s)){if(typeof r!=`string`)throw Error(`Cannot use higher-order sections without the original template`);s=s.call(t.view,r.slice(e[3],e[5]),c),s!=null&&(o+=s)}else o+=this.renderTokens(e[4],t,n,r,i);return o}},F.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||_i(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},F.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,``),i=e.split(`
|
|
4
4
|
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=r+i[a]);return i.join(`
|
|
5
|
-
`)},F.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=vi(n)?n(e[1]):n[e[1]];if(a!=null){var o=e[6],s=e[5],c=e[4],l=a;s==0&&c&&(l=this.indentPartial(a,c,o));var u=this.parse(l,i);return this.renderTokens(u,t,n,l,r)}}},F.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},F.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||I.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===I.escape?String(i):r(i)},F.prototype.rawValue=function(e){return e[1]},F.prototype.getConfigTags=function(e){if(_i(e))return e;if(e&&typeof e==`object`)return e.tags},F.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!_i(e))return e.escape};var I={name:`mustache.js`,version:`4.2.0`,tags:[`{{`,`}}`],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){zi.templateCache=e},get templateCache(){return zi.templateCache}},zi=new F;I.clearCache=function(){return zi.clearCache()},I.parse=function(e,t){return zi.parse(e,t)},I.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+yi(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return zi.render(e,t,n,r)},I.escape=Oi,I.Scanner=Li,I.Context=Ri,I.Writer=F;function Bi(){I.escape=e=>e}var Vi=e=>{let t=e.split(``),n=[],r=(e,n)=>{for(let r=n;r<t.length;r+=1)if(e.includes(t[r]))return r;return-1},i=0;for(;i<t.length;)if(t[i]===`{`&&i+1<t.length&&t[i+1]===`{`)n.push({type:`literal`,text:`{`}),i+=2;else if(t[i]===`}`&&i+1<t.length&&t[i+1]===`}`)n.push({type:`literal`,text:`}`}),i+=2;else if(t[i]===`{`){let e=r(`}`,i);if(e<0)throw Error(`Unclosed '{' in template.`);n.push({type:`variable`,name:t.slice(i+1,e).join(``)}),i=e+1}else if(t[i]===`}`)throw Error(`Single '}' in template.`);else{let e=r(`{}`,i),a=(e<0?t.slice(i):t.slice(i,e)).join(``);n.push({type:`literal`,text:a}),i=e<0?t.length:e}return n},Hi=(e,t=[])=>{let n=[];for(let r of e)if(r[0]===`name`){let e=r[1].includes(`.`)?r[1].split(`.`)[0]:r[1];n.push({type:`variable`,name:e})}else if([`#`,`&`,`^`,`>`].includes(r[0])){if(n.push({type:`variable`,name:r[1]}),r[0]===`#`&&r.length>4&&Array.isArray(r[4])){let e=[...t,r[1]],i=Hi(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},Ui=e=>(Bi(),Hi(I.parse(e))),Wi=(e,t)=>Vi(e).reduce((e,n)=>{if(n.type===`variable`){if(n.name in t)return e+(typeof t[n.name]==`string`?t[n.name]:JSON.stringify(t[n.name]));throw Error(`(f-string) Missing value for input ${n.name}`)}return e+n.text},``),Gi=(e,t)=>(Bi(),I.render(e,t)),Ki={"f-string":Wi,mustache:Gi},qi={"f-string":Vi,mustache:Ui},Ji=(e,t,n)=>{try{return Ki[t](e,n)}catch(e){throw
|
|
5
|
+
`)},F.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=vi(n)?n(e[1]):n[e[1]];if(a!=null){var o=e[6],s=e[5],c=e[4],l=a;s==0&&c&&(l=this.indentPartial(a,c,o));var u=this.parse(l,i);return this.renderTokens(u,t,n,l,r)}}},F.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},F.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||I.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===I.escape?String(i):r(i)},F.prototype.rawValue=function(e){return e[1]},F.prototype.getConfigTags=function(e){if(_i(e))return e;if(e&&typeof e==`object`)return e.tags},F.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!_i(e))return e.escape};var I={name:`mustache.js`,version:`4.2.0`,tags:[`{{`,`}}`],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){zi.templateCache=e},get templateCache(){return zi.templateCache}},zi=new F;I.clearCache=function(){return zi.clearCache()},I.parse=function(e,t){return zi.parse(e,t)},I.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+yi(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return zi.render(e,t,n,r)},I.escape=Oi,I.Scanner=Li,I.Context=Ri,I.Writer=F;function Bi(){I.escape=e=>e}var Vi=e=>{let t=e.split(``),n=[],r=(e,n)=>{for(let r=n;r<t.length;r+=1)if(e.includes(t[r]))return r;return-1},i=0;for(;i<t.length;)if(t[i]===`{`&&i+1<t.length&&t[i+1]===`{`)n.push({type:`literal`,text:`{`}),i+=2;else if(t[i]===`}`&&i+1<t.length&&t[i+1]===`}`)n.push({type:`literal`,text:`}`}),i+=2;else if(t[i]===`{`){let e=r(`}`,i);if(e<0)throw Error(`Unclosed '{' in template.`);n.push({type:`variable`,name:t.slice(i+1,e).join(``)}),i=e+1}else if(t[i]===`}`)throw Error(`Single '}' in template.`);else{let e=r(`{}`,i),a=(e<0?t.slice(i):t.slice(i,e)).join(``);n.push({type:`literal`,text:a}),i=e<0?t.length:e}return n},Hi=(e,t=[])=>{let n=[];for(let r of e)if(r[0]===`name`){let e=r[1].includes(`.`)?r[1].split(`.`)[0]:r[1];n.push({type:`variable`,name:e})}else if([`#`,`&`,`^`,`>`].includes(r[0])){if(n.push({type:`variable`,name:r[1]}),r[0]===`#`&&r.length>4&&Array.isArray(r[4])){let e=[...t,r[1]],i=Hi(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},Ui=e=>(Bi(),Hi(I.parse(e))),Wi=(e,t)=>Vi(e).reduce((e,n)=>{if(n.type===`variable`){if(n.name in t)return e+(typeof t[n.name]==`string`?t[n.name]:JSON.stringify(t[n.name]));throw Error(`(f-string) Missing value for input ${n.name}`)}return e+n.text},``),Gi=(e,t)=>(Bi(),I.render(e,t)),Ki={"f-string":Wi,mustache:Gi},qi={"f-string":Vi,mustache:Ui},Ji=(e,t,n)=>{try{return Ki[t](e,n)}catch(e){throw Ze(e,`INVALID_PROMPT_INPUT`)}},Yi=(e,t)=>qi[t](e),Xi=(e,t,n)=>{if(!(t in Ki))throw Error(`Invalid template format. Got \`${t}\`;
|
|
6
6
|
should be one of ${Object.keys(Ki)}`);try{let r=Object.fromEntries(n.map(e=>[e,`foo`]));Array.isArray(e)?e.forEach(e=>{if(e.type===`text`&&`text`in e&&typeof e.text==`string`)Ji(e.text,t,r);else if(e.type===`image_url`){if(typeof e.image_url==`string`)Ji(e.image_url,t,r);else if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`){let n=e.image_url.url;Ji(n,t,r)}}else throw Error(`Invalid message template received. ${JSON.stringify(e,null,2)}`)}):Ji(e,t,r)}catch(e){throw Error(`Invalid prompt schema: ${e.message}`)}},Zi=class e extends hi{static lc_name(){return`PromptTemplate`}template;templateFormat=`f-string`;validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),e.templateFormat===`mustache`&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){if(this.templateFormat===`mustache`)throw Error(`Mustache templates cannot be validated.`);let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),Xi(this.template,this.templateFormat,e)}}_getPromptType(){return`prompt`}async format(e){let t=await this.mergePartialAndUserVariables(e);return Ji(this.template,this.templateFormat,t)}static fromExamples(t,n,r,i=`
|
|
7
7
|
|
|
8
8
|
`,a=``){return new e({inputVariables:r,template:[a,...t,n].join(i)})}static fromTemplate(t,n){let{templateFormat:r=`f-string`,...i}=n??{},a=new Set;return Yi(t,r).forEach(e=>{e.type===`variable`&&a.add(e.name)}),new e({inputVariables:[...a],templateFormat:r,template:t,...i})}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}serialize(){if(this.outputParser!==void 0)throw Error(`Cannot serialize a prompt template with an output parser`);return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(t){if(!t.template)throw Error(`Prompt template must have a template`);return new e({inputVariables:t.input_variables,template:t.template,templateFormat:t.template_format})}},Qi=class e extends mi{static lc_name(){return`ImagePromptTemplate`}lc_namespace=[`langchain_core`,`prompts`,`image`];template;templateFormat=`f-string`;validateTemplate=!0;additionalContentFields;constructor(e){if(super(e),this.template=e.template,this.templateFormat=e.templateFormat??this.templateFormat,this.validateTemplate=e.validateTemplate??this.validateTemplate,this.additionalContentFields=e.additionalContentFields,this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),Xi([{type:`image_url`,image_url:this.template}],this.templateFormat,e)}}_getPromptType(){return`prompt`}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}async format(e){let t={};for(let[n,r]of Object.entries(this.template))typeof r==`string`?t[n]=Ji(r,this.templateFormat,e):t[n]=r;let n=e.url||t.url,r=e.detail||t.detail;if(!n)throw Error(`Must provide either an image URL.`);if(typeof n!=`string`)throw Error(`url must be a string.`);let i={url:n};return r&&(i.detail=r),i}async formatPromptValue(e){return new en(await this.format(e))}},$i=class extends E{lc_namespace=[`langchain_core`,`prompts`,`dict`];lc_serializable=!0;template;templateFormat;inputVariables;static lc_name(){return`DictPromptTemplate`}constructor(e){let t=e.templateFormat??`f-string`,n=ea(e.template,t);super({inputVariables:n,...e}),this.template=e.template,this.templateFormat=t,this.inputVariables=n}async format(e){return ta(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:`prompt`})}};function ea(e,t){let n=[];for(let r of Object.values(e))if(typeof r==`string`)Yi(r,t).forEach(e=>{e.type===`variable`&&n.push(e.name)});else if(Array.isArray(r))for(let e of r)typeof e==`string`?Yi(e,t).forEach(e=>{e.type===`variable`&&n.push(e.name)}):typeof e==`object`&&n.push(...ea(e,t));else typeof r==`object`&&r&&n.push(...ea(r,t));return Array.from(new Set(n))}function ta(e,t,n){let r={};for(let[i,a]of Object.entries(e))if(typeof a==`string`)r[i]=Ji(a,n,t);else if(Array.isArray(a)){let e=[];for(let r of a)typeof r==`string`?e.push(Ji(r,n,t)):typeof r==`object`&&e.push(ta(r,t,n));r[i]=e}else typeof a==`object`&&a?r[i]=ta(a,t,n):r[i]=a;return r}var na=class extends E{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;async invoke(e,t){return this._callWithConfig(e=>this.formatMessages(e),e,{...t,runType:`prompt`})}},ra=class extends na{static lc_name(){return`MessagesPlaceholder`}variableName;optional;constructor(e){typeof e==`string`&&(e={variableName:e}),super(e),this.variableName=e.variableName,this.optional=e.optional??!1}get inputVariables(){return[this.variableName]}async formatMessages(e){let t=e[this.variableName];if(this.optional&&!t)return[];if(!t){let e=Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw e.name=`InputFormatError`,e}let n;try{n=Array.isArray(t)?t.map(g):[g(t)]}catch(e){let n=typeof t==`string`?t:JSON.stringify(t,null,2),r=Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${n}`,`Additional message: ${e.message}`].join(`
|
|
9
9
|
|
|
10
|
-
`));throw r.name=`InputFormatError`,r.lc_error_code=e.lc_error_code,r}return n}},ia=class extends na{prompt;constructor(e){`prompt`in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},aa=class extends mi{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){return new Qt(await this.formatMessages(e))}},oa=class extends ia{static lc_name(){return`ChatMessagePromptTemplate`}role;constructor(e,t){`prompt`in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new Je(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(Zi.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function sa(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).length===1&&`text`in e&&typeof e.text==`string`}function ca(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`image_url`in e&&(typeof e.image_url==`string`||typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`)}var la=class extends na{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw Error(`Can not invoke _messageClass from inside _StringImageMessagePromptTemplate`)}chatMessageClass;constructor(e,t){if(`prompt`in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let e=[];this.prompt.forEach(t=>{`inputVariables`in t&&(e=e.concat(t.inputVariables))}),this.inputVariables=e}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){let n=t.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw Error(`No message class defined`)}getRoleFromMessageClass(e){switch(e){case`HumanMessage`:return`human`;case`AIMessage`:return`ai`;case`SystemMessage`:return`system`;case`ChatMessage`:return`chat`;default:throw Error(`Invalid message class name`)}}static fromTemplate(e,t){if(typeof e==`string`)return new this(Zi.fromTemplate(e,t));let n=[];for(let r of e)if(typeof r==`string`)n.push(Zi.fromTemplate(r,t));else if(r!==null)if(sa(r)){let e=``;typeof r.text==`string`&&(e=r.text??``);let i={...t,additionalContentFields:r};n.push(Zi.fromTemplate(e,i))}else if(ca(r)){let e=r.image_url??``,i,a=[];if(typeof e==`string`){let n;n=t?.templateFormat===`mustache`?Ui(e):Vi(e);let o=n.flatMap(e=>e.type===`variable`?[e.name]:[]);if((o?.length??0)>0){if(o.length>1)throw Error(`Only one format variable allowed per image template.\nGot: ${o}\nFrom: ${e}`);a=[o[0]]}else a=[];e={url:e},i=new Qi({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof e==`object`){if(`url`in e){let n;n=t?.templateFormat===`mustache`?Ui(e.url):Vi(e.url),a=n.flatMap(e=>e.type===`variable`?[e.name]:[])}else a=[];i=new Qi({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else throw Error(`Invalid image template`);n.push(i)}else typeof r==`object`&&n.push(new $i({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof hi){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let n of this.prompt){let r={};if(!(`inputVariables`in n))throw Error(`Prompt ${n} does not have inputVariables defined.`);for(let t of n.inputVariables)r||={[t]:e[t]},r={...r,[t]:e[t]};if(n instanceof hi){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),e!==``&&t.push({...i,type:`text`,text:e})}else if(n instanceof Qi){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),t.push({...i,type:`image_url`,image_url:e})}else if(n instanceof $i){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),t.push({...i,...e})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},ua=class extends la{static _messageClass(){return O}static lc_name(){return`HumanMessagePromptTemplate`}},da=class extends la{static _messageClass(){return w}static lc_name(){return`AIMessagePromptTemplate`}},fa=class extends la{static _messageClass(){return D}static lc_name(){return`SystemMessagePromptTemplate`}};function pa(e){return typeof e.formatMessages==`function`}function ma(e,t){if(pa(e)||s(e))return e;if(Array.isArray(e)&&e[0]===`placeholder`){let n=e[1];if(t?.templateFormat===`mustache`&&typeof n==`string`&&n.slice(0,2)===`{{`&&n.slice(-2)===`}}`)return new ra({variableName:n.slice(2,-2),optional:!0});if(typeof n==`string`&&n[0]===`{`&&n[n.length-1]===`}`)return new ra({variableName:n.slice(1,-1),optional:!0});throw Error(`Invalid placeholder template for format ${t?.templateFormat??`"f-string"`}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat===`mustache`?`double`:`single`} curly braces.`)}let n=g(e),r;if(r=typeof n.content==`string`?n.content:n.content.map(e=>`text`in e?{...e,text:e.text}:`image_url`in e?{...e,image_url:e.image_url}:e),n._getType()===`human`)return ua.fromTemplate(r,t);if(n._getType()===`ai`)return da.fromTemplate(r,t);if(n._getType()===`system`)return fa.fromTemplate(r,t);if(Je.isInstance(n))return oa.fromTemplate(n.content,n.role,t);throw Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function ha(e){return e.constructor.lc_name()===`MessagesPlaceholder`}var ga=class e extends aa{static lc_name(){return`ChatPromptTemplate`}get lc_aliases(){return{promptMessages:`messages`}}promptMessages;validateTemplate=!0;templateFormat=`f-string`;constructor(e){if(super(e),e.templateFormat===`mustache`&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let e=new Set;for(let t of this.promptMessages)if(!(t instanceof gt))for(let n of t.inputVariables)e.add(n);let t=this.inputVariables,n=new Set(this.partialVariables?t.concat(Object.keys(this.partialVariables)):t),r=new Set([...n].filter(t=>!e.has(t)));if(r.size>0)throw Error(`Input variables \`${[...r]}\` are not used in any of the prompt messages.`);let i=new Set([...e].filter(e=>!n.has(e)));if(i.size>0)throw Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return`chat`}async _parseImagePrompts(e,t){return typeof e.content==`string`||(e.content=await Promise.all(e.content.map(async e=>{if(e.type!==`image_url`)return e;let n=``;typeof e.image_url==`string`?n=e.image_url:typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`&&(n=e.image_url.url);let r=await Zi.fromTemplate(n,{templateFormat:this.templateFormat}).format(t);return typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url?e.image_url.url=r:e.image_url=r,e}))),e}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=[];for(let e of this.promptMessages)if(e instanceof gt)n.push(await this._parseImagePrompts(e,t));else{let r;r=this.templateFormat===`mustache`?{...t}:e.inputVariables.reduce((n,r)=>{if(!(r in t)&&!(ha(e)&&e.optional))throw
|
|
10
|
+
`));throw r.name=`InputFormatError`,r.lc_error_code=e.lc_error_code,r}return n}},ia=class extends na{prompt;constructor(e){`prompt`in e||(e={prompt:e}),super(e),this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},aa=class extends mi{constructor(e){super(e)}async format(e){return(await this.formatPromptValue(e)).toString()}async formatPromptValue(e){return new Qt(await this.formatMessages(e))}},oa=class extends ia{static lc_name(){return`ChatMessagePromptTemplate`}role;constructor(e,t){`prompt`in e||(e={prompt:e,role:t}),super(e),this.role=e.role}async format(e){return new Je(await this.prompt.format(e),this.role)}static fromTemplate(e,t,n){return new this(Zi.fromTemplate(e,{templateFormat:n?.templateFormat}),t)}};function sa(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.keys(e).length===1&&`text`in e&&typeof e.text==`string`}function ca(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`image_url`in e&&(typeof e.image_url==`string`||typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`)}var la=class extends na{lc_namespace=[`langchain_core`,`prompts`,`chat`];lc_serializable=!0;inputVariables=[];additionalOptions={};prompt;messageClass;static _messageClass(){throw Error(`Can not invoke _messageClass from inside _StringImageMessagePromptTemplate`)}chatMessageClass;constructor(e,t){if(`prompt`in e||(e={prompt:e}),super(e),this.prompt=e.prompt,Array.isArray(this.prompt)){let e=[];this.prompt.forEach(t=>{`inputVariables`in t&&(e=e.concat(t.inputVariables))}),this.inputVariables=e}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=t??this.additionalOptions}createMessage(e){let t=this.constructor;if(t._messageClass())return new(t._messageClass())({content:e});if(t.chatMessageClass){let n=t.chatMessageClass();return new n({content:e,role:this.getRoleFromMessageClass(n.lc_name())})}else throw Error(`No message class defined`)}getRoleFromMessageClass(e){switch(e){case`HumanMessage`:return`human`;case`AIMessage`:return`ai`;case`SystemMessage`:return`system`;case`ChatMessage`:return`chat`;default:throw Error(`Invalid message class name`)}}static fromTemplate(e,t){if(typeof e==`string`)return new this(Zi.fromTemplate(e,t));let n=[];for(let r of e)if(typeof r==`string`)n.push(Zi.fromTemplate(r,t));else if(r!==null)if(sa(r)){let e=``;typeof r.text==`string`&&(e=r.text??``);let i={...t,additionalContentFields:r};n.push(Zi.fromTemplate(e,i))}else if(ca(r)){let e=r.image_url??``,i,a=[];if(typeof e==`string`){let n;n=t?.templateFormat===`mustache`?Ui(e):Vi(e);let o=n.flatMap(e=>e.type===`variable`?[e.name]:[]);if((o?.length??0)>0){if(o.length>1)throw Error(`Only one format variable allowed per image template.\nGot: ${o}\nFrom: ${e}`);a=[o[0]]}else a=[];e={url:e},i=new Qi({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else if(typeof e==`object`){if(`url`in e){let n;n=t?.templateFormat===`mustache`?Ui(e.url):Vi(e.url),a=n.flatMap(e=>e.type===`variable`?[e.name]:[])}else a=[];i=new Qi({template:e,inputVariables:a,templateFormat:t?.templateFormat,additionalContentFields:r})}else throw Error(`Invalid image template`);n.push(i)}else typeof r==`object`&&n.push(new $i({template:r,templateFormat:t?.templateFormat}));return new this({prompt:n,additionalOptions:t})}async format(e){if(this.prompt instanceof hi){let t=await this.prompt.format(e);return this.createMessage(t)}else{let t=[];for(let n of this.prompt){let r={};if(!(`inputVariables`in n))throw Error(`Prompt ${n} does not have inputVariables defined.`);for(let t of n.inputVariables)r||={[t]:e[t]},r={...r,[t]:e[t]};if(n instanceof hi){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),e!==``&&t.push({...i,type:`text`,text:e})}else if(n instanceof Qi){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),t.push({...i,type:`image_url`,image_url:e})}else if(n instanceof $i){let e=await n.format(r),i;`additionalContentFields`in n&&(i=n.additionalContentFields),t.push({...i,...e})}}return this.createMessage(t)}}async formatMessages(e){return[await this.format(e)]}},ua=class extends la{static _messageClass(){return O}static lc_name(){return`HumanMessagePromptTemplate`}},da=class extends la{static _messageClass(){return w}static lc_name(){return`AIMessagePromptTemplate`}},fa=class extends la{static _messageClass(){return D}static lc_name(){return`SystemMessagePromptTemplate`}};function pa(e){return typeof e.formatMessages==`function`}function ma(e,t){if(pa(e)||s(e))return e;if(Array.isArray(e)&&e[0]===`placeholder`){let n=e[1];if(t?.templateFormat===`mustache`&&typeof n==`string`&&n.slice(0,2)===`{{`&&n.slice(-2)===`}}`)return new ra({variableName:n.slice(2,-2),optional:!0});if(typeof n==`string`&&n[0]===`{`&&n[n.length-1]===`}`)return new ra({variableName:n.slice(1,-1),optional:!0});throw Error(`Invalid placeholder template for format ${t?.templateFormat??`"f-string"`}: "${e[1]}". Expected a variable name surrounded by ${t?.templateFormat===`mustache`?`double`:`single`} curly braces.`)}let n=g(e),r;if(r=typeof n.content==`string`?n.content:n.content.map(e=>`text`in e?{...e,text:e.text}:`image_url`in e?{...e,image_url:e.image_url}:e),n._getType()===`human`)return ua.fromTemplate(r,t);if(n._getType()===`ai`)return da.fromTemplate(r,t);if(n._getType()===`system`)return fa.fromTemplate(r,t);if(Je.isInstance(n))return oa.fromTemplate(n.content,n.role,t);throw Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function ha(e){return e.constructor.lc_name()===`MessagesPlaceholder`}var ga=class e extends aa{static lc_name(){return`ChatPromptTemplate`}get lc_aliases(){return{promptMessages:`messages`}}promptMessages;validateTemplate=!0;templateFormat=`f-string`;constructor(e){if(super(e),e.templateFormat===`mustache`&&e.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,e),this.validateTemplate){let e=new Set;for(let t of this.promptMessages)if(!(t instanceof gt))for(let n of t.inputVariables)e.add(n);let t=this.inputVariables,n=new Set(this.partialVariables?t.concat(Object.keys(this.partialVariables)):t),r=new Set([...n].filter(t=>!e.has(t)));if(r.size>0)throw Error(`Input variables \`${[...r]}\` are not used in any of the prompt messages.`);let i=new Set([...e].filter(e=>!n.has(e)));if(i.size>0)throw Error(`Input variables \`${[...i]}\` are used in prompt messages but not in the prompt template.`)}}_getPromptType(){return`chat`}async _parseImagePrompts(e,t){return typeof e.content==`string`||(e.content=await Promise.all(e.content.map(async e=>{if(e.type!==`image_url`)return e;let n=``;typeof e.image_url==`string`?n=e.image_url:typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url&&typeof e.image_url.url==`string`&&(n=e.image_url.url);let r=await Zi.fromTemplate(n,{templateFormat:this.templateFormat}).format(t);return typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url?e.image_url.url=r:e.image_url=r,e}))),e}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=[];for(let e of this.promptMessages)if(e instanceof gt)n.push(await this._parseImagePrompts(e,t));else{let r;r=this.templateFormat===`mustache`?{...t}:e.inputVariables.reduce((n,r)=>{if(!(r in t)&&!(ha(e)&&e.optional))throw Ze(Error(`Missing value for input variable \`${r.toString()}\``),`INVALID_PROMPT_INPUT`);return n[r]=t[r],n},{});let i=await e.formatMessages(r);n=n.concat(i)}return n}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}static fromTemplate(e,t){let n=new ua({prompt:Zi.fromTemplate(e,t)});return this.fromMessages([n])}static fromMessages(t,n){let r=t.reduce((t,r)=>t.concat(r instanceof e?r.promptMessages:[ma(r,n)]),[]),i=t.reduce((t,n)=>n instanceof e?Object.assign(t,n.partialVariables):t,Object.create(null)),a=new Set;for(let e of r)if(!(e instanceof gt))for(let t of e.inputVariables)t in i||a.add(t);return new this({...n,inputVariables:[...a],promptMessages:r,partialVariables:i,templateFormat:n?.templateFormat})}},_a=class e extends hi{lc_serializable=!1;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
|
|
11
11
|
|
|
12
12
|
`;prefix=``;templateFormat=`f-string`;validateTemplate=!0;constructor(e){if(super(e),Object.assign(this,e),this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),Xi(this.prefix+this.suffix,this.templateFormat,e)}}_getPromptType(){return`few_shot`}static lc_name(){return`FewShotPromptTemplate`}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=await Promise.all(n.map(e=>this.examplePrompt.format(e)));return Ji([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}serialize(){if(this.exampleSelector||!this.examples)throw Error(`Serializing an example selector is not currently supported`);if(this.outputParser!==void 0)throw Error(`Serializing an output parser is not currently supported`);return{_type:this._getPromptType(),input_variables:this.inputVariables,example_prompt:this.examplePrompt.serialize(),example_separator:this.exampleSeparator,suffix:this.suffix,prefix:this.prefix,template_format:this.templateFormat,examples:this.examples}}static async deserialize(t){let{example_prompt:n}=t;if(!n)throw Error(`Missing example prompt`);let r=await Zi.deserialize(n),i;if(Array.isArray(t.examples))i=t.examples;else throw Error(`Invalid examples format. Only list or string are supported.`);return new e({inputVariables:t.input_variables,examplePrompt:r,examples:i,exampleSeparator:t.example_separator,prefix:t.prefix,suffix:t.suffix,templateFormat:t.template_format})}},va=class e extends aa{lc_serializable=!0;examples;exampleSelector;examplePrompt;suffix=``;exampleSeparator=`
|
|
13
13
|
|
|
14
14
|
`;prefix=``;templateFormat=`f-string`;validateTemplate=!0;_getPromptType(){return`few_shot_chat`}static lc_name(){return`FewShotChatMessagePromptTemplate`}constructor(e){if(super(e),this.examples=e.examples,this.examplePrompt=e.examplePrompt,this.exampleSeparator=e.exampleSeparator??`
|
|
15
15
|
|
|
16
|
-
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??``,this.suffix=e.suffix??``,this.templateFormat=e.templateFormat??`f-string`,this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),Xi(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t);n=n.map(e=>{let t={};return this.examplePrompt.inputVariables.forEach(n=>{t[n]=e[n]}),t});let r=[];for(let e of n){let t=await this.examplePrompt.formatMessages(e);r.push(...t)}return r}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=(await Promise.all(n.map(e=>this.examplePrompt.formatMessages(e)))).flat().map(e=>e.content);return Ji([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}},ya=class e extends mi{static lc_name(){return`PipelinePromptTemplate`}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name),t=this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}async formatPipelinePrompts(t){let n=await this.mergePartialAndUserVariables(t);for(let{name:t,prompt:r}of this.pipelinePrompts){let i=e.extractRequiredInputValues(n,r.inputVariables);r instanceof ga?n[t]=await r.formatMessages(i):n[t]=await r.format(i)}return e.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(t){let n={...this};return n.inputVariables=this.inputVariables.filter(e=>!(e in t)),n.partialVariables={...this.partialVariables??{},...t},new e(n)}serialize(){throw Error(`Not implemented.`)}_getPromptType(){return`pipeline`}};function ba(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function xa(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var Sa=class e extends ga{schema;method;lc_namespace=[`langchain_core`,`prompts`,`structured`];get lc_aliases(){return{...super.lc_aliases,schema:`schema_`}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(ba(e))return super.pipe(e.withStructuredOutput(this.schema));if(xa(e)&&ba(e.bound))return super.pipe(new rt({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`)}static fromMessagesAndSchema(t,n,r){return e.fromMessages(t,{schema:n,method:r})}},Ca={};j(Ca,{AIMessagePromptTemplate:()=>da,BaseChatPromptTemplate:()=>aa,BaseMessagePromptTemplate:()=>na,BaseMessageStringPromptTemplate:()=>ia,BasePromptTemplate:()=>mi,BaseStringPromptTemplate:()=>hi,ChatMessagePromptTemplate:()=>oa,ChatPromptTemplate:()=>ga,DEFAULT_FORMATTER_MAPPING:()=>Ki,DEFAULT_PARSER_MAPPING:()=>qi,DictPromptTemplate:()=>$i,FewShotChatMessagePromptTemplate:()=>va,FewShotPromptTemplate:()=>_a,HumanMessagePromptTemplate:()=>ua,ImagePromptTemplate:()=>Qi,MessagesPlaceholder:()=>ra,PipelinePromptTemplate:()=>ya,PromptTemplate:()=>Zi,StructuredPrompt:()=>Sa,SystemMessagePromptTemplate:()=>fa,checkValidTemplate:()=>Xi,interpolateFString:()=>Wi,interpolateMustache:()=>Gi,parseFString:()=>Vi,parseMustache:()=>Ui,parseTemplate:()=>Yi,renderTemplate:()=>Ji});var wa={};j(wa,{BaseDocumentCompressor:()=>Ta});var Ta=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},Ea={and:`and`,or:`or`,not:`not`},L={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},Da=class{},Oa=class{accept(e){if(this.exprName===`Operation`)return e.visitOperation(this);if(this.exprName===`Comparison`)return e.visitComparison(this);if(this.exprName===`StructuredQuery`)return e.visitStructuredQuery(this);throw Error(`Unknown Expression type`)}},ka=class extends Oa{},Aa=class extends ka{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},ja=class extends ka{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},Ma=class extends Oa{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function Na(e){return e&&typeof e==`object`&&!Array.isArray(e)}function Pa(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:Na(e)&&Object.keys(e).length===0:!0}function Fa(e){if(typeof e==`number`)return e%1==0;if(typeof e==`string`){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1==0&&t.toString()===e}return!1}function Ia(e){if(typeof e==`number`)return e%1!=0;if(typeof e==`string`){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!=0&&t.toString()===e}return!1}function La(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function Ra(e){return typeof e==`boolean`}function za(e){let t;if(La(e))t=e;else if(Fa(e))t=parseInt(e,10);else if(Ia(e))t=parseFloat(e);else if(Ra(e))t=!!e;else throw Error(`Unsupported value type`);return t}var Ba=class extends Da{},Va=class extends Ba{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[Ea.and,Ea.or],this.allowedComparators=e?.allowedComparators??[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte]}formatFunction(e){if(e in L){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(`, `)}`)}else if(e in Ea){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(`, `)}`)}else throw Error(`Unknown comparator or operator`);return`$${e}`}visitOperation(e){let t=e.args?.map(e=>e.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:za(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!(Pa(e)&&Pa(t))){if(Pa(e)||n===`replace`)return Pa(t)?void 0:t;if(Pa(t))return r?e:n===`and`?void 0:e;if(n===`and`)return{$and:[e,t]};if(n===`or`)return{$or:[e,t]};throw Error(`Unknown merge type`)}}},Ha=class extends Ba{allowedOperators=[Ea.and,Ea.or];allowedComparators=[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case`number`:return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case`boolean`:return[L.eq,L.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case L.eq:return(e,t)=>e===t;case L.ne:return(e,t)=>e!==t;case L.gt:return(e,t)=>e>t;case L.gte:return(e,t)=>e>=t;case L.lt:return(e,t)=>e<t;case L.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case Ea.and:return(e,t)=>e&&t;case Ea.or:return(e,t)=>e||t;default:throw Error(`Unknown operator`)}}visitOperation(e){let{operator:t,args:n}=e;if(this.allowedOperators.includes(t)){let e=this.getOperatorFunction(t);return t=>n?n.reduce((n,r)=>{let i=r.accept(this);if(typeof i==`function`)return e(n,i(t));throw Error(`Filter is not a function`)},!0):!0}else throw Error(`Operator not allowed`)}visitComparison(e){let{comparator:t,attribute:n,value:r}=e,i=[L.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof r).includes(t))throw Error(`'${t}' comparator not allowed to be used with ${typeof r}`);let e=this.getComparatorFunction(t);return a=>{let o=a.metadata[n];return o===void 0?!!i.includes(t):e(o,za(r))}}else throw Error(`Comparator not allowed`)}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!=`function`)throw Error(`Structured query filter is not a function`);return{filter:t}}mergeFilters(e,t,n=`and`){if(!(Pa(e)&&Pa(t))){if(Pa(e)||n===`replace`)return Pa(t)?void 0:t;if(Pa(t))return n===`and`?void 0:e;if(n===`and`)return n=>e(n)&&t(n);if(n===`or`)return n=>e(n)||t(n);throw Error(`Unknown merge type`)}}},Ua={};j(Ua,{BaseTranslator:()=>Ba,BasicTranslator:()=>Va,Comparators:()=>L,Comparison:()=>Aa,Expression:()=>Oa,FilterDirective:()=>ka,FunctionalTranslator:()=>Ha,Operation:()=>ja,Operators:()=>Ea,StructuredQuery:()=>Ma,Visitor:()=>Da,castValue:()=>za,isBoolean:()=>Ra,isFilterEmpty:()=>Pa,isFloat:()=>Ia,isInt:()=>Fa,isObject:()=>Na,isString:()=>La});var Wa={};j(Wa,{RunCollectorCallbackHandler:()=>Ga});var Ga=class extends a{name=`run_collector`;exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},Ka={},qa={};j(qa,{context:()=>Ja});function Ja(e,...t){let n=e.raw,r=``;for(let e=0;e<n.length;e++){let i=n[e].replace(/\\\n[ \t]*/g,``).replace(/\\`/g,"`").replace(/\\\$/g,`$`).replace(/\\\{/g,`{`);if(r+=i,e<t.length){let n=Ya(t[e],r);r+=typeof n==`string`?n:JSON.stringify(n)}}return r=Xa(r),r=r.trim(),r=r.replace(/\\n/g,`
|
|
16
|
+
`,this.exampleSelector=e.exampleSelector,this.prefix=e.prefix??``,this.suffix=e.suffix??``,this.templateFormat=e.templateFormat??`f-string`,this.validateTemplate=e.validateTemplate??!0,this.examples!==void 0&&this.exampleSelector!==void 0)throw Error(`Only one of 'examples' and 'example_selector' should be provided`);if(this.examples===void 0&&this.exampleSelector===void 0)throw Error(`One of 'examples' and 'example_selector' should be provided`);if(this.validateTemplate){let e=this.inputVariables;this.partialVariables&&(e=e.concat(Object.keys(this.partialVariables))),Xi(this.prefix+this.suffix,this.templateFormat,e)}}async getExamples(e){if(this.examples!==void 0)return this.examples;if(this.exampleSelector!==void 0)return this.exampleSelector.selectExamples(e);throw Error(`One of 'examples' and 'example_selector' should be provided`)}async formatMessages(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t);n=n.map(e=>{let t={};return this.examplePrompt.inputVariables.forEach(n=>{t[n]=e[n]}),t});let r=[];for(let e of n){let t=await this.examplePrompt.formatMessages(e);r.push(...t)}return r}async format(e){let t=await this.mergePartialAndUserVariables(e),n=await this.getExamples(t),r=(await Promise.all(n.map(e=>this.examplePrompt.formatMessages(e)))).flat().map(e=>e.content);return Ji([this.prefix,...r,this.suffix].join(this.exampleSeparator),this.templateFormat,t)}async partial(t){let n=this.inputVariables.filter(e=>!(e in t)),r={...this.partialVariables??{},...t};return new e({...this,inputVariables:n,partialVariables:r})}},ya=class e extends mi{static lc_name(){return`PipelinePromptTemplate`}pipelinePrompts;finalPrompt;constructor(e){super({...e,inputVariables:[]}),this.pipelinePrompts=e.pipelinePrompts,this.finalPrompt=e.finalPrompt,this.inputVariables=this.computeInputValues()}computeInputValues(){let e=this.pipelinePrompts.map(e=>e.name),t=this.pipelinePrompts.map(t=>t.prompt.inputVariables.filter(t=>!e.includes(t))).flat();return[...new Set(t)]}static extractRequiredInputValues(e,t){return t.reduce((t,n)=>(t[n]=e[n],t),{})}async formatPipelinePrompts(t){let n=await this.mergePartialAndUserVariables(t);for(let{name:t,prompt:r}of this.pipelinePrompts){let i=e.extractRequiredInputValues(n,r.inputVariables);r instanceof ga?n[t]=await r.formatMessages(i):n[t]=await r.format(i)}return e.extractRequiredInputValues(n,this.finalPrompt.inputVariables)}async formatPromptValue(e){return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(e))}async format(e){return this.finalPrompt.format(await this.formatPipelinePrompts(e))}async partial(t){let n={...this};return n.inputVariables=this.inputVariables.filter(e=>!(e in t)),n.partialVariables={...this.partialVariables??{},...t},new e(n)}serialize(){throw Error(`Not implemented.`)}_getPromptType(){return`pipeline`}};function ba(e){return typeof e==`object`&&!!e&&`withStructuredOutput`in e&&typeof e.withStructuredOutput==`function`}function xa(e){return typeof e==`object`&&!!e&&`lc_id`in e&&Array.isArray(e.lc_id)&&e.lc_id.join(`/`)===`langchain_core/runnables/RunnableBinding`}var Sa=class e extends ga{schema;method;lc_namespace=[`langchain_core`,`prompts`,`structured`];get lc_aliases(){return{...super.lc_aliases,schema:`schema_`}}constructor(e){super(e),this.schema=e.schema,this.method=e.method}pipe(e){if(ba(e))return super.pipe(e.withStructuredOutput(this.schema));if(xa(e)&&ba(e.bound))return super.pipe(new nt({bound:e.bound.withStructuredOutput(this.schema,...this.method?[{method:this.method}]:[]),kwargs:e.kwargs??{},config:e.config,configFactories:e.configFactories}));throw Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`)}static fromMessagesAndSchema(t,n,r){return e.fromMessages(t,{schema:n,method:r})}},Ca={};j(Ca,{AIMessagePromptTemplate:()=>da,BaseChatPromptTemplate:()=>aa,BaseMessagePromptTemplate:()=>na,BaseMessageStringPromptTemplate:()=>ia,BasePromptTemplate:()=>mi,BaseStringPromptTemplate:()=>hi,ChatMessagePromptTemplate:()=>oa,ChatPromptTemplate:()=>ga,DEFAULT_FORMATTER_MAPPING:()=>Ki,DEFAULT_PARSER_MAPPING:()=>qi,DictPromptTemplate:()=>$i,FewShotChatMessagePromptTemplate:()=>va,FewShotPromptTemplate:()=>_a,HumanMessagePromptTemplate:()=>ua,ImagePromptTemplate:()=>Qi,MessagesPlaceholder:()=>ra,PipelinePromptTemplate:()=>ya,PromptTemplate:()=>Zi,StructuredPrompt:()=>Sa,SystemMessagePromptTemplate:()=>fa,checkValidTemplate:()=>Xi,interpolateFString:()=>Wi,interpolateMustache:()=>Gi,parseFString:()=>Vi,parseMustache:()=>Ui,parseTemplate:()=>Yi,renderTemplate:()=>Ji});var wa={};j(wa,{BaseDocumentCompressor:()=>Ta});var Ta=class{static isBaseDocumentCompressor(e){return e?.compressDocuments!==void 0}},Ea={and:`and`,or:`or`,not:`not`},L={eq:`eq`,ne:`ne`,lt:`lt`,gt:`gt`,lte:`lte`,gte:`gte`},Da=class{},Oa=class{accept(e){if(this.exprName===`Operation`)return e.visitOperation(this);if(this.exprName===`Comparison`)return e.visitComparison(this);if(this.exprName===`StructuredQuery`)return e.visitStructuredQuery(this);throw Error(`Unknown Expression type`)}},ka=class extends Oa{},Aa=class extends ka{exprName=`Comparison`;constructor(e,t,n){super(),this.comparator=e,this.attribute=t,this.value=n}},ja=class extends ka{exprName=`Operation`;constructor(e,t){super(),this.operator=e,this.args=t}},Ma=class extends Oa{exprName=`StructuredQuery`;constructor(e,t){super(),this.query=e,this.filter=t}};function Na(e){return e&&typeof e==`object`&&!Array.isArray(e)}function Pa(e){return e?typeof e==`string`&&e.length>0||typeof e==`function`?!1:Na(e)&&Object.keys(e).length===0:!0}function Fa(e){if(typeof e==`number`)return e%1==0;if(typeof e==`string`){let t=parseInt(e,10);return!Number.isNaN(t)&&t%1==0&&t.toString()===e}return!1}function Ia(e){if(typeof e==`number`)return e%1!=0;if(typeof e==`string`){let t=parseFloat(e);return!Number.isNaN(t)&&t%1!=0&&t.toString()===e}return!1}function La(e){return typeof e==`string`&&(Number.isNaN(parseFloat(e))||parseFloat(e).toString()!==e)}function Ra(e){return typeof e==`boolean`}function za(e){let t;if(La(e))t=e;else if(Fa(e))t=parseInt(e,10);else if(Ia(e))t=parseFloat(e);else if(Ra(e))t=!!e;else throw Error(`Unsupported value type`);return t}var Ba=class extends Da{},Va=class extends Ba{allowedOperators;allowedComparators;constructor(e){super(),this.allowedOperators=e?.allowedOperators??[Ea.and,Ea.or],this.allowedComparators=e?.allowedComparators??[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte]}formatFunction(e){if(e in L){if(this.allowedComparators.length>0&&this.allowedComparators.indexOf(e)===-1)throw Error(`Comparator ${e} not allowed. Allowed comparators: ${this.allowedComparators.join(`, `)}`)}else if(e in Ea){if(this.allowedOperators.length>0&&this.allowedOperators.indexOf(e)===-1)throw Error(`Operator ${e} not allowed. Allowed operators: ${this.allowedOperators.join(`, `)}`)}else throw Error(`Unknown comparator or operator`);return`$${e}`}visitOperation(e){let t=e.args?.map(e=>e.accept(this));return{[this.formatFunction(e.operator)]:t}}visitComparison(e){return{[e.attribute]:{[this.formatFunction(e.comparator)]:za(e.value)}}}visitStructuredQuery(e){let t={};return e.filter&&(t={filter:e.filter.accept(this)}),t}mergeFilters(e,t,n=`and`,r=!1){if(!(Pa(e)&&Pa(t))){if(Pa(e)||n===`replace`)return Pa(t)?void 0:t;if(Pa(t))return r?e:n===`and`?void 0:e;if(n===`and`)return{$and:[e,t]};if(n===`or`)return{$or:[e,t]};throw Error(`Unknown merge type`)}}},Ha=class extends Ba{allowedOperators=[Ea.and,Ea.or];allowedComparators=[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];formatFunction(){throw Error(`Not implemented`)}getAllowedComparatorsForType(e){switch(e){case`string`:return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case`number`:return[L.eq,L.ne,L.gt,L.gte,L.lt,L.lte];case`boolean`:return[L.eq,L.ne];default:throw Error(`Unsupported data type: ${e}`)}}getComparatorFunction(e){switch(e){case L.eq:return(e,t)=>e===t;case L.ne:return(e,t)=>e!==t;case L.gt:return(e,t)=>e>t;case L.gte:return(e,t)=>e>=t;case L.lt:return(e,t)=>e<t;case L.lte:return(e,t)=>e<=t;default:throw Error(`Unknown comparator`)}}getOperatorFunction(e){switch(e){case Ea.and:return(e,t)=>e&&t;case Ea.or:return(e,t)=>e||t;default:throw Error(`Unknown operator`)}}visitOperation(e){let{operator:t,args:n}=e;if(this.allowedOperators.includes(t)){let e=this.getOperatorFunction(t);return t=>n?n.reduce((n,r)=>{let i=r.accept(this);if(typeof i==`function`)return e(n,i(t));throw Error(`Filter is not a function`)},!0):!0}else throw Error(`Operator not allowed`)}visitComparison(e){let{comparator:t,attribute:n,value:r}=e,i=[L.ne];if(this.allowedComparators.includes(t)){if(!this.getAllowedComparatorsForType(typeof r).includes(t))throw Error(`'${t}' comparator not allowed to be used with ${typeof r}`);let e=this.getComparatorFunction(t);return a=>{let o=a.metadata[n];return o===void 0?!!i.includes(t):e(o,za(r))}}else throw Error(`Comparator not allowed`)}visitStructuredQuery(e){if(!e.filter)return{};let t=e.filter?.accept(this);if(typeof t!=`function`)throw Error(`Structured query filter is not a function`);return{filter:t}}mergeFilters(e,t,n=`and`){if(!(Pa(e)&&Pa(t))){if(Pa(e)||n===`replace`)return Pa(t)?void 0:t;if(Pa(t))return n===`and`?void 0:e;if(n===`and`)return n=>e(n)&&t(n);if(n===`or`)return n=>e(n)||t(n);throw Error(`Unknown merge type`)}}},Ua={};j(Ua,{BaseTranslator:()=>Ba,BasicTranslator:()=>Va,Comparators:()=>L,Comparison:()=>Aa,Expression:()=>Oa,FilterDirective:()=>ka,FunctionalTranslator:()=>Ha,Operation:()=>ja,Operators:()=>Ea,StructuredQuery:()=>Ma,Visitor:()=>Da,castValue:()=>za,isBoolean:()=>Ra,isFilterEmpty:()=>Pa,isFloat:()=>Ia,isInt:()=>Fa,isObject:()=>Na,isString:()=>La});var Wa={};j(Wa,{RunCollectorCallbackHandler:()=>Ga});var Ga=class extends a{name=`run_collector`;exampleId;tracedRuns;constructor({exampleId:e}={}){super({_awaitHandler:!0}),this.exampleId=e,this.tracedRuns=[]}async persistRun(e){let t={...e};t.reference_example_id=this.exampleId,this.tracedRuns.push(t)}},Ka={},qa={};j(qa,{context:()=>Ja});function Ja(e,...t){let n=e.raw,r=``;for(let e=0;e<n.length;e++){let i=n[e].replace(/\\\n[ \t]*/g,``).replace(/\\`/g,"`").replace(/\\\$/g,`$`).replace(/\\\{/g,`{`);if(r+=i,e<t.length){let n=Ya(t[e],r);r+=typeof n==`string`?n:JSON.stringify(n)}}return r=Xa(r),r=r.trim(),r=r.replace(/\\n/g,`
|
|
17
17
|
`),r}function Ya(e,t){if(typeof e!=`string`||!e.includes(`
|
|
18
18
|
`))return e;let n=t.slice(t.lastIndexOf(`
|
|
19
19
|
`)+1).match(/^(\s+)/);if(n){let t=n[1];return e.replace(/\n/g,`\n${t}`)}return e}function Xa(e){let t=e.split(`
|
|
@@ -21,13 +21,13 @@ import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{n as t}from"./chunk-QWQY
|
|
|
21
21
|
`)}var Za={};j(Za,{EventStreamContentType:()=>Qa,convertEventStreamToIterableReadableDataStream:()=>ao,getBytes:()=>$a,getLines:()=>to,getMessages:()=>no});var Qa=`text/event-stream`;async function $a(e,t){if(e instanceof ReadableStream){let n=e.getReader();for(;;){let e=await n.read();if(e.done){t(new Uint8Array,!0);break}t(e.value)}}else try{for await(let n of e)t(new Uint8Array(n));t(new Uint8Array,!0)}catch(e){throw Error([`Parsing event source stream failed.`,`Ensure your implementation of fetch returns a web or Node readable stream.`,`Error: ${e.message}`].join(`
|
|
22
22
|
`))}}var eo=function(e){return e[e.NewLine=10]=`NewLine`,e[e.CarriageReturn=13]=`CarriageReturn`,e[e.Space=32]=`Space`,e[e.Colon=58]=`Colon`,e}(eo||{});function to(e){let t,n,r,i=!1;return function(a,o){if(o){e(a,0,!0);return}t===void 0?(t=a,n=0,r=-1):t=ro(t,a);let s=t.length,c=0;for(;n<s;){i&&=(t[n]===eo.NewLine&&(c=++n),!1);let a=-1;for(;n<s&&a===-1;++n)switch(t[n]){case eo.Colon:r===-1&&(r=n-c);break;case eo.CarriageReturn:i=!0;case eo.NewLine:a=n;break}if(a===-1)break;e(t.subarray(c,a),r),c=n,r=-1}c===s?t=void 0:c!==0&&(t=t.subarray(c),n-=c)}}function no(e,t,n){let r=io(),i=new TextDecoder;return function(a,o,s){if(s){oo(r)||(e?.(r),r=io());return}if(a.length===0)e?.(r),r=io();else if(o>0){let e=i.decode(a.subarray(0,o)),s=o+(a[o+1]===eo.Space?2:1),c=i.decode(a.subarray(s));switch(e){case`data`:r.data=r.data?r.data+`
|
|
23
23
|
`+c:c;break;case`event`:r.event=c;break;case`id`:t?.(r.id=c);break;case`retry`:{let e=parseInt(c,10);Number.isNaN(e)||n?.(r.retry=e);break}}}}}function ro(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function io(){return{data:``,event:``,id:``,retry:void 0}}function ao(e,t){let n=new ReadableStream({async start(n){let r=no(e=>{if(e.event===`error`)throw Error(e.data??`Unspecified event streaming error.`);e.event===`metadata`?t?.(e):e.data&&n.enqueue(e.data)});await $a(e,to((e,t,i)=>{r(e,t,i),i&&n.close()}))}});return Pe.fromReadableStream(n)}function oo(e){return e.data===``&&e.event===``&&e.id===``&&e.retry===void 0}var so={};function co(e,t){let n=0,r=0,i=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],r+=e[a]*e[a],i+=t[a]*t[a];return n/(Math.sqrt(r)*Math.sqrt(i))}function lo(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function uo(e,t){let n=0;for(let r=0;r<e.length;r++)n+=(e[r]-t[r])*(e[r]-t[r]);return n}function fo(e,t){return Math.sqrt(uo(e,t))}var po={};j(po,{cosineSimilarity:()=>go,euclideanDistance:()=>vo,innerProduct:()=>_o,matrixFunc:()=>mo,maximalMarginalRelevance:()=>yo,normalize:()=>ho});function mo(e,t,n){if(e.length===0||e[0].length===0||t.length===0||t[0].length===0)return[[]];if(e[0].length!==t[0].length)throw Error(`Number of columns in X and Y must be the same. X has shape ${[e.length,e[0].length]} and Y has shape ${[t.length,t[0].length]}.`);return e.map(e=>t.map(t=>n(e,t)).map(e=>Number.isNaN(e)?0:e))}function ho(e,t=!1){let n=xo(e);return e.map(e=>e.map(e=>t?1-e/n:e/n))}function go(e,t){return mo(e,t,co)}function _o(e,t){return mo(e,t,lo)}function vo(e,t){return mo(e,t,fo)}function yo(e,t,n=.5,r=4){if(Math.min(r,t.length)<=0)return[];let i=go(Array.isArray(e[0])?e:[e],t)[0],a=bo(i).maxIndex,o=[t[a]],s=[a];for(;s.length<Math.min(r,t.length);){let e=-1/0,r=-1,a=go(t,o);i.forEach((t,i)=>{if(s.includes(i))return;let o=Math.max(...a[i]),c=n*t-(1-n)*o;c>e&&(e=c,r=i)}),o.push(t[r]),s.push(r)}return s}function bo(e){if(e.length===0)return{maxIndex:-1,maxValue:NaN};let t=e[0],n=0;for(let r=1;r<e.length;r+=1)e[r]>t&&(n=r,t=e[r]);return{maxIndex:n,maxValue:t}}function xo(e){return e.reduce((e,t)=>Math.max(e,bo(t).maxValue),0)}var So=class extends Xt{_combineLLMOutput(){return[]}_llmType(){return`fake`}async _generate(e,t,n){if(t?.stop?.length)return{generations:[{message:new w(t.stop[0]),text:t.stop[0]}]};let r=e.map(e=>typeof e.content==`string`?e.content:JSON.stringify(e.content,null,2)).join(`
|
|
24
|
-
`);return await n?.handleLLMNewToken(r),{generations:[{message:new w(r),text:r}],llmOutput:{}}}},Co=class e extends Xt{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:fe(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:fe(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:fe(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:fe(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new w({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new Le({message:new we({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new w(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new Le({message:new we({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},wo=class e extends Xt{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new w(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new Le({message:new we({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:fe(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:fe(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:fe(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:fe(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return We.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},To=class extends cn{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},Eo=class extends cn{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Do=class extends pn{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},Oo=class extends pn{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},ko=class extends gr{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new O(e))}async addAIMessage(e){this.messages.push(new w(e))}async clear(){this.messages=[]}},Ao=class extends _r{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},jo=class extends a{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},Mo=class extends qt{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},No=class extends Ar{lc_namespace=[`test`,`fake`];output=[new Br({pageContent:`foo`}),new Br({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},Po=class extends E{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},Fo=class extends on{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},Io=class extends a{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},Lo=class e extends Nr{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??co}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>n?n(new Br({metadata:e.metadata,pageContent:e.content})):!0);return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new Br({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new Br({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},Ro={};j(Ro,{FakeChatMessageHistory:()=>ko,FakeChatModel:()=>So,FakeEmbeddings:()=>Eo,FakeLLM:()=>Do,FakeListChatMessageHistory:()=>Ao,FakeListChatModel:()=>wo,FakeRetriever:()=>No,FakeRunnable:()=>Po,FakeSplitIntoListParser:()=>Mo,FakeStreamingChatModel:()=>Co,FakeStreamingLLM:()=>Oo,FakeTool:()=>Fo,FakeTracer:()=>jo,FakeVectorStore:()=>Lo,SingleRunExtractor:()=>Io,SyntheticEmbeddings:()=>To});var zo={};j(zo,{agents:()=>mr,caches:()=>Gt,callbacks__base:()=>le,callbacks__manager:()=>ge,callbacks__promises:()=>d,chat_history:()=>hr,document_loaders__base:()=>Fr,document_loaders__langsmith:()=>Lr,documents:()=>Ur,embeddings:()=>ln,errors:()=>it,example_selectors:()=>$r,index:()=>yr,indexing:()=>ci,language_models__base:()=>Ht,language_models__chat_models:()=>Vt,language_models__llms:()=>dn,language_models__profile:()=>li,load__serializable:()=>u,memory:()=>br,messages:()=>Xe,messages__tool:()=>Oe,output_parsers:()=>Nt,output_parsers__openai_functions:()=>pi,output_parsers__openai_tools:()=>fn,outputs:()=>at,prompt_values:()=>$t,prompts:()=>Ca,retrievers:()=>kr,retrievers__document_compressors:()=>wa,runnables:()=>Kt,runnables__graph:()=>De,singletons:()=>me,stores:()=>Er,structured_query:()=>Ua,tools:()=>an,tracers__base:()=>Be,tracers__console:()=>Ue,tracers__log_stream:()=>Ae,tracers__run_collector:()=>Wa,tracers__tracer_langchain:()=>se,types__stream:()=>Ka,utils__async_caller:()=>nt,utils__chunk_array:()=>un,utils__context:()=>qa,utils__env:()=>y,utils__event_source_parse:()=>Za,utils__format:()=>so,utils__function_calling:()=>Yt,utils__hash:()=>Wt,utils__json_patch:()=>Rt,utils__json_schema:()=>ht,utils__math:()=>po,utils__stream:()=>Ye,utils__testing:()=>Ro,utils__tiktoken:()=>Jt,utils__types:()=>Lt,vectorstores:()=>jr});var Bo=50;function Vo(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function Ho(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:a,secretsFromEnv:o,path:s,depth:c,maxDepth:l}=this,u=s.join(`.`);if(c>l)throw Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>Ho.call({...this,path:[...s,`${t}`],depth:c+1},e)));let d=e;if(oe(d))return He(d);if(`lc`in d&&`type`in d&&`id`in d&&d.lc===1&&d.type===`secret`){let[e]=d.id;if(e in a)return a[e];if(o){let t=Se(e);if(t)return t}throw Error(`Missing secret "${e}" at ${u}`)}if(`lc`in d&&`type`in d&&`id`in d&&d.lc===1&&d.type===`not_implemented`){let e=JSON.stringify(d);throw Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${e}`)}if(`lc`in d&&`type`in d&&`id`in d&&`kwargs`in d&&d.lc===1&&d.type===`constructor`){let e=d,a=JSON.stringify(e),[o,...l]=e.id.slice().reverse(),p=l.reverse(),m={langchain_core:zo,langchain:r},h=null,g=[p.join(`/`)];p[0]===`langchain_community`&&g.push([`langchain`,...p.slice(1)].join(`/`));let _=g.find(e=>e in t);if(pr.concat(n).includes(p.join(`/`))||_)if(_!==void 0)h=await t[_];else throw Error(`Missing key "${p.join(`/`)}" for ${u} in load(optionalImportsMap={})`);else{let e;if(p[0]===`langchain`||p[0]===`langchain_core`)e=m[p[0]],p.shift();else throw Error(`Invalid namespace: ${u} -> ${a}`);if(p.length===0)throw Error(`Invalid namespace: ${u} -> ${a}`);let t;do{if(t=p.join(`__`),t in e)break;p.pop()}while(p.length>0);t in e&&(h=e[t])}if(typeof h!=`object`||!h)throw Error(`Invalid namespace: ${u} -> ${a}`);let v=h[o]??Object.values(h).find(e=>typeof e==`function`&&f(e)===o);if(typeof v!=`function`)throw Error(`Invalid identifer: ${u} -> ${a}`);let y=new v(ze(await Ho.call({...this,path:[...s,`kwargs`],depth:c+1},e.kwargs),i,Vo(v)));return Object.defineProperty(y.constructor,`name`,{value:o}),y}let p={};for(let[e,t]of Object.entries(d))p[e]=await Ho.call({...this,path:[...s,e],depth:c+1},t);return p}async function Uo(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??Bo};return Ho.call(r,n)}function Wo(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function Go(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>Go(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await Go(r);if(t.lc===2&&t.type===`undefined`)return;if(t.lc===2&&t.type===`constructor`&&Array.isArray(t.id))try{let e=t.id[t.id.length-1],n;switch(e){case`Set`:n=Set;break;case`Map`:n=Map;break;case`RegExp`:n=RegExp;break;case`Error`:n=Error;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(Wo(t))return Uo(JSON.stringify(t));return t}}return e}function Ko(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function qo(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof Set||e instanceof Map?Ko(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?Ko(RegExp,void 0,[e.source,e.flags]):e instanceof Error?Ko(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args}:e}var Jo=class{_dumps(e){return new TextEncoder().encode(lr(e,(e,t)=>qo(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return Go(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function Yo(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=Yo(e[n]));return t}function Xo(){return{v:4,id:Qn(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Zo(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:Yo(e.versions_seen)}}function Qo(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function $o(...e){return e.reduce((e,t,n)=>n===0?t:Qo(e,t)>=0?e:t)}var es={[er]:-1,[tr]:-2,[nr]:-3,[rr]:-4},ts=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function ns(e){if(e.length===0)throw new ts(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new ts(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new ts(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new ts(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new ts(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var rs=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){ns(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},is=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,as=class extends rs{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=is(e)}get isRunning(){return this.running}async batch(e){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},os=class{serde=new Jo;constructor(e){this.serde=e||this.serde}};function ss(e){return e!=null&&e.lg_is_channel===!0}var cs=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===N.unminifiable_name)return!1;throw e}}equals(e){return this===e}},ls=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function us(e){if(e[ls]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];ss(r)&&(t[n]=r)}return Object.assign(t,{[ls]:!0}),t}function ds(e,t){let n=us(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[ls]:!0}),r}function fs(e,t,n,r){let i;if(t===void 0)i=e.channel_values;else{i={};for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))try{i[e]=t[e].checkpoint()}catch(e){if(e.name!==N.unminifiable_name)throw e}}return{v:4,id:r?.id??Qn(n),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var ps=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,ms=class e extends cs{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;this.value===void 0&&([this.value]=t,t=t.slice(1));for(let e of t)this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new N;return this.value}checkpoint(){if(this.value===void 0)throw new N;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:ps(e)?this.operator===e.operator:!1}},hs=class e extends cs{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new P(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new N;return this.value[0]}checkpoint(){if(this.value.length===0)throw new N;return this.value[0]}isAvailable(){return this.value.length!==0}},gs=class e extends cs{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new N;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},_s=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},vs=function(e){return e?ys(e):new hs};vs.Root=e=>new _s(e);function ys(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new ms(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new ms(e.value,e.default):new hs}var R=`__start__`,z=`__end__`,bs=`__input__`,xs=`__error__`,Ss=`__pregel_ns_writes`,Cs=`__pregel_send`,ws=`__pregel_call`,Ts=`__pregel_read`,Es=`__pregel_checkpointer`,Ds=`__pregel_resuming`,Os=`__pregel_task_id`,ks=`__pregel_stream`,As=`__pregel_resume_value`,js=`__pregel_resume_map`,Ms=`__pregel_scratchpad`,Ns=`__pregel_previous`,Ps=`__pregel_durability`,Fs=`checkpoint_id`,Is=`checkpoint_ns`,Ls=`__pregel_node_finished`,Rs=`checkpoint_map`,zs=`__pregel_abort_signals`,B=`__interrupt__`,Bs=`__resume__`,Vs=`__no_writes__`,Hs=`__return__`,Us=`__previous__`,V=`langsmith:hidden`,Ws=`__self__`,Gs=`__pregel_tasks`,Ks=`__pregel_push`,qs=`__pregel_pull`,Js=`00000000-0000-0000-0000-000000000000`,Ys=[V,bs,B,Bs,xs,Vs,Cs,Ts,Es,Ps,ks,Ds,Os,ws,As,Ms,Ns,Rs,Is,Fs],Xs=Symbol.for(`langgraph.command`),Zs=class{[Xs];constructor(e){this[Xs]=e}};function Qs(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var H=class{lg_name=`Send`;node;args;constructor(e,t){this.node=e,this.args=ec(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function U(e){return e instanceof H}function $s(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[B])}var W=class extends Zs{lg_name=`Command`;lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT=`__parent__`;constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?ec(e.goto):[ec(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update==`object`&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`)?this.update:[[`__root__`,this.update]]}toJSON(){let e;return e=typeof this.goto==`string`?this.goto:U(this.goto)?this.goto.toJSON():this.goto?.map(e=>typeof e==`string`?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function G(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function ec(e,t=new Map){if(typeof e==`object`&&e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach((e,r)=>{n[r]=ec(e,t)});else if(G(e)&&!(e instanceof W))n=new W(e),t.set(e,n);else if(Qs(e)&&!(e instanceof H))n=new H(e.node,e.args),t.set(e,n);else if(G(e)||U(e))n=e,t.set(e,n);else if(`lc_serializable`in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=ec(i,t)}return n}return e}var tc=[`tags`,`metadata`,`callbacks`,`configurable`],nc=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`],rc=25;function ic(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:rc,configurable:{}},n=c.getRunnableConfig();if(n!==void 0){for(let[e,r]of Object.entries(n))if(r!==void 0)if(tc.includes(e)){let n;n=Array.isArray(r)?[...r]:typeof r==`object`?e===`callbacks`&&`copy`in r&&typeof r.copy==`function`?r.copy():{...r}:r,t[e]=n}else t[e]=r}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r!==void 0&&nc.includes(e)&&(t[e]=r);for(let[e,n]of Object.entries(t.configurable))t.metadata=t.metadata??{},!e.startsWith(`__`)&&(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&!(e in t.metadata)&&(t.metadata[e]=n);return t}function ac(){return c.getRunnableConfig()}function oc(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function sc(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var K=e=>BigInt(e),q=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),cc=K(`0x9E3779B1`),lc=K(`0x85EBCA77`),uc=K(`0xC2B2AE3D`),dc=K(`0x9E3779B185EBCA87`),fc=K(`0xC2B2AE3D27D4EB4F`),pc=K(`0x165667B19E3779F9`),mc=K(`0x85EBCA77C2B2AE63`),hc=K(`0x27D4EB2F165667C5`),gc=K(`0x165667919E3779F9`),_c=K(`0x9FB21C651E98DF25`),vc=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return q(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),yc=(K(1)<<K(128))-K(1),J=(K(1)<<K(64))-K(1),bc=(K(1)<<K(32))-K(1),xc=64,Sc=xc/8,Cc=8,wc=4;function Tc(e){if(!e)throw Error(`Assert failed`)}function Ec(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function Dc(e){let t=e;return t=(t&K(65535))<<K(16)|(t&K(4294901760))>>K(16),t=(t&K(16711935))<<K(8)|(t&K(4278255360))>>K(8),t}function Oc(e,t){return(e&bc)*(t&bc)&J}function kc(e,t){return(e<<t|e>>K(32)-t)&bc}function Ac(e,t,n){for(let r=0;r<Sc;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=Oc(a,a>>K(32))}return e}function jc(e,t,n,r){for(let i=0;i<r;i+=1)Ac(e,q(t,i*xc),q(n,i*8));return e}function Mc(e,t){for(let n=0;n<Sc;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=Uc(i,K(47)),i^=r,i*=cc,e[n]=i&J}return e}function Nc(e,t){return Lc(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(Cc,!0))}function Pc(e,t,n){let r=n;return r+=Nc(e.slice(0),q(t,0*wc)),r+=Nc(e.slice(2),q(t,4*wc)),r+=Nc(e.slice(4),q(t,8*wc)),r+=Nc(e.slice(6),q(t,12*wc)),Bc(r&J)}function Fc(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-xc)/8),s=xc*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=jc(a,q(t,e*s),n,o),a=i(a,q(n,n.byteLength-xc));{let e=Math.floor((t.byteLength-1-s*c)/xc);a=jc(a,q(t,c*s),n,e),a=r(a,q(t,t.byteLength-xc),q(n,n.byteLength-xc-7))}return a}function Ic(e,t){let n=new BigUint64Array([uc,dc,fc,pc,mc,lc,hc,cc]);Tc(e.byteLength>128),n=Fc(n,e,t,Ac,Mc),Tc(n.length*8==64);{let r=Pc(n,q(t,11),K(e.byteLength)*dc&J);return Pc(n,q(t,t.byteLength-xc-11),~(K(e.byteLength)*fc)&J)<<K(64)|r}}function Lc(e,t){let n=e*t&yc;return n&J^n>>K(64)}function Rc(e,t,n){return Lc((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&J,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&J)}function zc(e,t,n,r,i){let a=e&J,o=e>>K(64)&J;return a+=Rc(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=J,o+=Rc(n,q(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=J,o<<K(64)|a}function Bc(e){let t=e;return t^=t>>K(37),t*=gc,t&=J,t^=t>>K(32),t}function Vc(e){let t=e;return t^=t>>K(33),t*=fc,t&=J,t^=t>>K(29),t*=pc,t&=J,t^=t>>K(32),t}function Hc(e,t,n){let r=e.byteLength;Tc(r>0&&r<=3);let i=K(e.getUint8(r-1))|K(r<<8)|K(e.getUint8(0)<<16)|K(e.getUint8(r>>1)<<24),a=(i^(K(t.getUint32(0,!0))^K(t.getUint32(4,!0)))+n)&J,o=(K(t.getUint32(8,!0))^K(t.getUint32(12,!0)))-n;return(Vc((kc(Dc(i),K(13))^o)&J)&J)<<K(64)|Vc(a)}function Uc(e,t){return e^e>>t}function Wc(e,t,n){let r=e.byteLength;Tc(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((K(i)|K(a)<<K(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&J)*(dc+(K(r)<<K(2)))&yc;return o+=(o&J)<<K(65),o&=yc,o^=o>>K(67),Uc(Uc(o&J,K(35))*_c&J,K(28))|Bc(o>>K(64))<<K(64)}}function Gc(e,t,n){let r=e.byteLength;Tc(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&J,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&J,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*dc,l=(c&J)+(K(r-1)<<K(54));c=c&(yc^J)|l,s^=a,c+=s+(s&bc)*(lc-K(1))<<K(64),c&=yc,c^=Ec(c>>K(64));let u=(c&J)*fc;return u+=(c>>K(64))*fc<<K(64),u&=yc,Bc(u&J)|Bc(u>>K(64))<<K(64)}}function Kc(e,t){let n=e.byteLength;return Tc(n<=16),n>8?Gc(e,vc,t):n>=4?Wc(e,vc,t):n>0?Hc(e,vc,t):Vc(t^vc.getBigUint64(64,!0)^vc.getBigUint64(72,!0))|Vc(t^vc.getBigUint64(80,!0)^vc.getBigUint64(88,!0))<<K(64)}function qc(e){return~e+K(1)&J}function Jc(e,t,n){let r=K(e.byteLength)*dc&J,i=K(e.byteLength-1)/K(32);for(;i>=0;){let a=Number(i);r=zc(r,q(e,16*a),q(e,e.byteLength-16*(a+1)),q(t,32*a),n),i-=K(1)}let a=r+(r>>K(64))&J;a=Bc(a);let o=(r&J)*dc+(r>>K(64))*mc+(K(e.byteLength)-n&J)*fc;return o&=J,o=qc(Bc(o)),a|o<<K(64)}function Yc(e,t,n){let r=K(e.byteLength)*dc&J;for(let i=32;i<160;i+=32)r=zc(r,q(e,i-32),q(e,i-16),q(t,i-32),n);r=Bc(r&J)|Bc(r>>K(64))<<K(64);for(let i=160;i<=e.byteLength;i+=32)r=zc(r,q(e,i-32),q(e,i-16),q(t,3+i-160),n);r=zc(r,q(e,e.byteLength-16),q(e,e.byteLength-32),q(t,103),qc(n));let i=r+(r>>K(64))&J;i=Bc(i);let a=(r&J)*dc+(r>>K(64))*mc+(K(e.byteLength)-n&J)*fc;return a&=J,a=qc(Bc(a)),i|a<<K(64)}function Xc(e,t=K(0)){let n=new TextEncoder,r=q(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?Kc(r,t):i<=128?Jc(r,vc,t):i<=240?Yc(r,vc,t):Ic(r,vc))}function Zc(e){return/^[0-9a-f]{32}$/.test(e)}function Qc(e){let t=c.getRunnableConfig();if(!t)throw Error(`Called interrupt() outside the context of a graph.`);let n=t.configurable;if(!n)throw Error(`No configurable found in config`);if(!n.__pregel_checkpointer)throw new Hn(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[Ms];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[Cs]?.([[Bs,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);let e=r.consumeNullResume();return r.resume.push(e),n[Cs]?.([[Bs,r.resume]]),e}let a=n[Is]?.split(`|`);throw new Un([{id:a?Xc(a.join(`|`)):void 0,value:e}])}var $c=class extends E{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,i)=>{let a=ke(t,{callbacks:n?.getChild()});c.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=ic(t),i=bt(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await c.runWithConfig(i,async()=>this.func(e,i)),E.isRunnable(n)&&this.recurse?await c.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*el(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function tl(e){let t=[];for await(let n of await e)t.push(n);return t}function nl(e){let t=[];for(let n of e)t.push(n);return t}function rl(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function il(e){return e!=null&&typeof e==`function`&&e instanceof Object.getPrototypeOf(async function*(){}).constructor}function al(e){return e!=null&&typeof e==`function`&&e instanceof Object.getPrototypeOf(function*(){}).constructor}function ol(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var sl={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function cl(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var ll=Symbol(`IS_WRITER`),Y=class e extends $c{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>U(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>dl(e)&&cl(e.value)?{mapper:e.mapper,value:t}:ul(e)&&cl(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(ul(e)){if(e.channel===`__pregel_tasks`)throw new P(`Cannot write to the reserved channel TASKS`);if(cl(e.value))throw new P(`PASSTHROUGH value must be replaced`)}if(dl(e)&&cl(e.value))throw new P(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(U(r))n.push([Gs,r]);else if(dl(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(ul(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(ol(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[Cs];r(n)}static isWriter(t){return t instanceof e||ll in t&&!!t[ll]}static registerWriter(e){return Object.defineProperty(e,ll,{value:!0})}};function ul(e){return e!==void 0&&typeof e.channel==`string`}function dl(e){return e!==void 0&&!ul(e)&&E.isRunnable(e.mapper)}var fl=class e extends $c{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[Ts];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},pl=new Ft,ml=class e extends rt{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=pl;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,tags:u,subgraphs:d,ends:f}=e,p=[...e.config?.tags?e.config.tags:[],...u??[]];super({...e,bound:e.bound??pl,config:{...e.config?e.config:{},tags:p}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=p,this.retryPolicy=c,this.cachePolicy=l,this.subgraphs=d,this.ends=f}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof Y&&e[e.length-2]instanceof Y;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new Y(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===pl&&e.length===0))return this.bound===pl&&e.length===1?e[0]:this.bound===pl?new qe({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new qe({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return Y.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===pl?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:ut(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function hl(e){return`steps`in e&&Array.isArray(e.steps)}function gl(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function _l(e){let t=[e];for(let e of t)if(gl(e))return e;else hl(e)&&t.push(...e.steps)}function vl(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===N.unminifiable_name){if(r)return e;if(n)return null}throw e}}function yl(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=vl(e,i,!n)}catch(e){if(e.name===N.unminifiable_name)continue}return r}else return vl(e,t)}function*bl(e,t){if(e.graph===W.PARENT)throw new P(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(U(e))yield[Js,Gs,e];else if(typeof e==`string`)yield[Js,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(Zc))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,Bs,e]}else yield[Js,Bs,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[Js,t,n];else for(let[t,n]of Object.entries(e.update))yield[Js,t,n]}}function*xl(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*Sl(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield yl(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield vl(n,e))}function*Cl(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===Hs).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}function wl(e){let t=typeof e[R];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function Tl(e,t){if(Object.keys(e).length>0){let n=wl(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function El(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function Dl(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function Ol(e,t){let n=t?.parents??{};return Object.keys(n).length>0?Dl(e,{[Rs]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function kl(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}var Al=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t},jl=class{func;name;input;retry;cache;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,callbacks:a}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.callbacks=a}};function Ml(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function Nl(e,t){return new qe({name:e,first:new $c({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new Y([{channel:Hs,value:sl}],[V])})}function Pl(e,t){return new $c({func:(e,n)=>t(e,n),name:e,trace:!1,recurse:!1})}var Fl=e=>e===void 0?1:e+1;function Il(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function Ll(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:$o(t,e[n]));return t}function Rl(e,t,n){let r=wl(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(V):t.includes(e.name));return a&&o}function zl(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=fs(e,i,-1),c=ds(i,s);Hl(Zo(s),c,[n],void 0,void 0),o=yl({...t,...c},r)}else o=yl(t,r);return o}function Bl(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!U(r))throw new P(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new P(`Invalid node name "${r.node}" in Send packet`)}e(n)}var Vl=new Set([Vs,Ks,Bs,B,Hs,xs]);function Hl(e,t,n,r,i){n.sort((e,t)=>{let n=e.path?.slice(0,3)||[],r=t.path?.slice(0,3)||[];for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let a=n.some(e=>e.triggers.length>0),o=us(t);for(let t of n){e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n])}let s=Ll(e.channel_versions),c=new Set(n.flatMap(e=>e.triggers).filter(e=>!Ys.includes(e))),l=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(s),l=!0);let u={};for(let e of n)for(let[t,n]of e.writes)Vl.has(t)||t in o&&(u[t]??=[],u[t].push(n));s!=null&&r!=null&&(s=l?r(s):s);let d=new Set;for(let[t,n]of Object.entries(u))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===P.unminifiable_name){let r=new P(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(s),i.isAvailable()&&d.add(t))}if(a)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!d.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(s),n.isAvailable()&&d.add(t))}if(a&&!Il(d,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(s),n.isAvailable()&&d.add(t))}return d}function*Ul(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function Wl(e,t,n,r,i,a,o){let s={},c=r[Gs];if(c?.isAvailable()){let l=c.get().length;for(let c=0;c<l;c+=1){let l=Gl([Ks,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}}for(let c of Ul(e,n,o)){let l=Gl([qs,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}return s}function Gl(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&Ml(e[e.length-1])){let p=e[e.length-1],m=Nl(p.name,p.func),h=[Ks],g=f===``?p.name:`${f}|${p.name}`,_=$n(JSON.stringify([g,c.toString(),p.name,Ks,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v};if(o){let e=[];return{name:p.name,input:p.input,proc:m,writes:e,config:ke(bt(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Os]:_,[Cs]:t=>Bl(t=>e.push(...t),r,t),[Ts]:(n,r=!1)=>zl(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[Es]:l??d.__pregel_checkpointer,[Rs]:{...d[Rs],[f]:t.id},[Ms]:Jl({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[js],namespaceHash:Xc(v)}),[Ns]:t.channel_values[Us],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:Xc((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[Ss,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[]}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[Gs].get();if(p<0||p>=m.length)return;let h=Qs(m[p])&&!U(m[p])?new H(m[p].node,m[p].args):m[p];if(!Qs(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[Ks],_=f===``?h.node:`${f}|${h.node}`,v=$n(JSON.stringify([_,c.toString(),h.node,Ks,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[];return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:ke(bt(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Os]:v,[Cs]:e=>Bl(e=>m.push(...e),r,e),[Ts]:(n,r=!1)=>zl(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[Es]:l??d.__pregel_checkpointer,[Rs]:{...d[Rs],[f]:t.id},[Ms]:Jl({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[js],namespaceHash:Xc(y)}),[Ns]:t.channel_values[Us],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:Xc((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[Ss,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters()}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=$n(JSON.stringify([e,c.toString(),p,qs,p]),t.id);if(n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=wl(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=Kl(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=$n(JSON.stringify([g,c.toString(),p,qs,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[];return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:ke(bt(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Os]:v,[Cs]:e=>Bl(e=>{g.push(...e)},r,e),[Ts]:(n,r=!1)=>zl(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[Es]:l??d.__pregel_checkpointer,[Rs]:{...d[Rs],[f]:t.id},[Ms]:Jl({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[js],namespaceHash:Xc(y)}),[Ns]:t.channel_values[Us],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:Xc((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[Ss,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters()}}}else return{id:v,name:p,interrupts:[],path:e}}}}function Kl(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=vl(t,i,!1)}catch(e){if(e.name===N.unminifiable_name)return;throw e}else if(i in t)try{r[n]=vl(t,i,!1)}catch(e){if(e.name===N.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=vl(t,i,!1),n=!0;break}catch(e){if(e.name===N.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function ql(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new H(e.node,n)}function Jl({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i}){let a=e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{let n=e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),a}};return o}var Yl={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},Xl=(e,t)=>`${e.start}${t}${e.end}`;function*Zl(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)})}function Ql(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function $l(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=Ql(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*eu(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:$l(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===B).map(e=>e[1])})}function*tu(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(_l))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:yl(t,n),metadata:r,next:i.map(e=>e.name),tasks:nu(i,a,u,s),parentConfig:o?c(o):void 0}}function nu(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?$l(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function ru(e,t,n){console.log([`${Xl(Yl.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(yl(t,n),null,2)].join(``))}function iu(e,t){let n=t.length;console.log([`${Xl(Yl.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${Xl(Yl.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
|
|
24
|
+
`);return await n?.handleLLMNewToken(r),{generations:[{message:new w(r),text:r}],llmOutput:{}}}},Co=class e extends Xt{sleep=50;responses=[];chunks=[];toolStyle=`openai`;thrownErrorString;tools=[];constructor({sleep:e=50,responses:t=[],chunks:n=[],toolStyle:r=`openai`,thrownErrorString:i,...a}){super(a),this.sleep=e,this.responses=t,this.chunks=n,this.toolStyle=r,this.thrownErrorString=i}_llmType(){return`fake`}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:fe(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:fe(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:fe(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:fe(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({sleep:this.sleep,responses:this.responses,chunks:this.chunks,toolStyle:this.toolStyle,thrownErrorString:this.thrownErrorString});return a.tools=n,a.withConfig({tools:i})}async _generate(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);return{generations:[{text:``,message:new w({content:this.responses?.[0]?.content??e[0].content??``,tool_calls:this.chunks?.[0]?.tool_calls})}]}}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);if(this.chunks?.length){for(let e of this.chunks){let r=new Le({message:new we({content:e.content,tool_calls:e.tool_calls,additional_kwargs:e.additional_kwargs??{}}),text:e.content?.toString()??``});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e.content,void 0,void 0,void 0,void 0,{chunk:r})}return}let r=this.responses?.[0]??new w(typeof e[0].content==`string`?e[0].content:``),i=typeof r.content==`string`?r.content:``;for(let e of i){await new Promise(e=>setTimeout(e,this.sleep));let r=new Le({message:new we({content:e}),text:e});if(t.signal?.aborted)break;yield r,await n?.handleLLMNewToken(e,void 0,void 0,void 0,void 0,{chunk:r})}}},wo=class e extends Xt{static lc_name(){return`FakeListChatModel`}lc_serializable=!0;responses;i=0;sleep;emitCustomEvent=!1;generationInfo;tools=[];toolStyle=`openai`;constructor(e){super(e);let{responses:t,sleep:n,emitCustomEvent:r,generationInfo:i}=e;this.responses=t,this.sleep=n,this.emitCustomEvent=r??this.emitCustomEvent,this.generationInfo=i}_combineLLMOutput(){return[]}_llmType(){return`fake-list`}async _generate(e,t,n){if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);if(this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0}),t?.stop?.length)return{generations:[this._formatGeneration(t.stop[0])]};{let e=this._currentResponse();return this._incrementResponse(),{generations:[this._formatGeneration(e)],llmOutput:{}}}}_formatGeneration(e){return{message:new w(e),text:e}}async*_streamResponseChunks(e,t,n){let r=this._currentResponse();this._incrementResponse(),this.emitCustomEvent&&await n?.handleCustomEvent(`some_test_event`,{someval:!0});let i=[...r];for(let e=0;e<i.length;e++){let r=i[e],a=e===i.length-1;if(await this._sleepIfRequested(),t?.thrownErrorString)throw Error(t.thrownErrorString);let o=this._createResponseChunk(r,a?this.generationInfo:void 0);if(t.signal?.aborted)break;yield o,n?.handleLLMNewToken(r)}}async _sleepIfRequested(){this.sleep!==void 0&&await this._sleep()}async _sleep(){return new Promise(e=>{setTimeout(()=>e(),this.sleep)})}_createResponseChunk(e,t){return new Le({message:new we({content:e}),text:e,generationInfo:t})}_currentResponse(){return this.responses[this.i]}_incrementResponse(){this.i<this.responses.length-1?this.i+=1:this.i=0}bindTools(t){let n=[...this.tools,...t],r=n.map(e=>{switch(this.toolStyle){case`openai`:return{type:`function`,function:{name:e.name,description:e.description,parameters:fe(e.schema)}};case`anthropic`:return{name:e.name,description:e.description,input_schema:fe(e.schema)};case`bedrock`:return{toolSpec:{name:e.name,description:e.description,inputSchema:fe(e.schema)}};case`google`:return{name:e.name,description:e.description,parameters:fe(e.schema)};default:throw Error(`Unsupported tool style: ${this.toolStyle}`)}}),i=this.toolStyle===`google`?[{functionDeclarations:r}]:r,a=new e({responses:this.responses,sleep:this.sleep,emitCustomEvent:this.emitCustomEvent,generationInfo:this.generationInfo});return a.tools=n,a.toolStyle=this.toolStyle,a.i=this.i,a.withConfig({tools:i})}withStructuredOutput(e,t){return We.from(async e=>{let t=await this.invoke(e);if(t.tool_calls?.[0]?.args)return t.tool_calls[0].args;if(typeof t.content==`string`)return JSON.parse(t.content);throw Error(`No structured output found`)})}},To=class extends cn{vectorSize;constructor(e){super(e??{}),this.vectorSize=e?.vectorSize??4}async embedDocuments(e){return Promise.all(e.map(e=>this.embedQuery(e)))}async embedQuery(e){let t=e;t=t.toLowerCase().replaceAll(/[^a-z ]/g,``);let n=t.length%this.vectorSize,r=n===0?0:this.vectorSize-n,i=t.length+r;t=t.padEnd(i,` `);let a=t.length/this.vectorSize,o=[];for(let e=0;e<t.length;e+=a)o.push(t.slice(e,e+a));return o.map(e=>{let t=0;for(let n=0;n<e.length;n+=1)t+=e===` `?0:e.charCodeAt(n);return t%26/26})}},Eo=class extends cn{constructor(e){super(e??{})}embedDocuments(e){return Promise.resolve(e.map(()=>[.1,.2,.3,.4]))}embedQuery(e){return Promise.resolve([.1,.2,.3,.4])}},Do=class extends pn{response;thrownErrorString;constructor(e){super(e),this.response=e.response,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.response??e;return await n?.handleLLMNewToken(r),r}},Oo=class extends pn{sleep=50;responses;thrownErrorString;constructor(e){super(e),this.sleep=e.sleep??this.sleep,this.responses=e.responses,this.thrownErrorString=e.thrownErrorString}_llmType(){return`fake`}async _call(e){if(this.thrownErrorString)throw Error(this.thrownErrorString);let t=this.responses?.[0];return this.responses=this.responses?.slice(1),t??e}async*_streamResponseChunks(e,t,n){if(this.thrownErrorString)throw Error(this.thrownErrorString);let r=this.responses?.[0];this.responses=this.responses?.slice(1);for(let t of r??e)await new Promise(e=>setTimeout(e,this.sleep)),yield{text:t,generationInfo:{}},await n?.handleLLMNewToken(t)}},ko=class extends gr{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async addUserMessage(e){this.messages.push(new O(e))}async addAIMessage(e){this.messages.push(new w(e))}async clear(){this.messages=[]}},Ao=class extends _r{lc_namespace=[`langchain_core`,`message`,`fake`];messages=[];constructor(){super()}async addMessage(e){this.messages.push(e)}async getMessages(){return this.messages}},jo=class extends a{name=`fake_tracer`;runs=[];constructor(){super()}persistRun(e){return this.runs.push(e),Promise.resolve()}},Mo=class extends qt{lc_namespace=[`tests`,`fake`];getFormatInstructions(){return``}async parse(e){return e.split(`,`).map(e=>e.trim())}},No=class extends Ar{lc_namespace=[`test`,`fake`];output=[new Br({pageContent:`foo`}),new Br({pageContent:`bar`})];constructor(e){super(),this.output=e?.output??this.output}async _getRelevantDocuments(e){return this.output}},Po=class extends E{lc_namespace=[`tests`,`fake`];returnOptions;constructor(e){super(e),this.returnOptions=e.returnOptions}async invoke(e,t){return this.returnOptions?t??{}:{input:e}}},Fo=class extends on{name;description;schema;constructor(e){super(e),this.name=e.name,this.description=e.description,this.schema=e.schema}async _call(e,t){return JSON.stringify(e)}},Io=class extends a{runPromiseResolver;runPromise;name=`single_run_extractor`;constructor(){super(),this.runPromise=new Promise(e=>{this.runPromiseResolver=e})}async persistRun(e){this.runPromiseResolver(e)}async extract(){return this.runPromise}},Lo=class e extends Nr{memoryVectors=[];similarity;_vectorstoreType(){return`memory`}constructor(e,{similarity:t,...n}={}){super(e,n),this.similarity=t??co}async addDocuments(e){let t=e.map(({pageContent:e})=>e);return this.addVectors(await this.embeddings.embedDocuments(t),e)}async addVectors(e,t){let n=e.map((e,n)=>({content:t[n].pageContent,embedding:e,metadata:t[n].metadata}));this.memoryVectors=this.memoryVectors.concat(n)}async similaritySearchVectorWithScore(e,t,n){let r=this.memoryVectors.filter(e=>n?n(new Br({metadata:e.metadata,pageContent:e.content})):!0);return r.map((t,n)=>({similarity:this.similarity(e,t.embedding),index:n})).sort((e,t)=>e.similarity>t.similarity?-1:0).slice(0,t).map(e=>[new Br({metadata:r[e.index].metadata,pageContent:r[e.index].content}),e.similarity])}static async fromTexts(t,n,r,i){let a=[];for(let e=0;e<t.length;e+=1){let r=Array.isArray(n)?n[e]:n,i=new Br({pageContent:t[e],metadata:r});a.push(i)}return e.fromDocuments(a,r,i)}static async fromDocuments(e,t,n){let r=new this(t,n);return await r.addDocuments(e),r}static async fromExistingIndex(e,t){return new this(e,t)}},Ro={};j(Ro,{FakeChatMessageHistory:()=>ko,FakeChatModel:()=>So,FakeEmbeddings:()=>Eo,FakeLLM:()=>Do,FakeListChatMessageHistory:()=>Ao,FakeListChatModel:()=>wo,FakeRetriever:()=>No,FakeRunnable:()=>Po,FakeSplitIntoListParser:()=>Mo,FakeStreamingChatModel:()=>Co,FakeStreamingLLM:()=>Oo,FakeTool:()=>Fo,FakeTracer:()=>jo,FakeVectorStore:()=>Lo,SingleRunExtractor:()=>Io,SyntheticEmbeddings:()=>To});var zo={};j(zo,{agents:()=>mr,caches:()=>Gt,callbacks__base:()=>le,callbacks__manager:()=>ge,callbacks__promises:()=>d,chat_history:()=>hr,document_loaders__base:()=>Fr,document_loaders__langsmith:()=>Lr,documents:()=>Ur,embeddings:()=>ln,errors:()=>rt,example_selectors:()=>$r,index:()=>yr,indexing:()=>ci,language_models__base:()=>Ht,language_models__chat_models:()=>Vt,language_models__llms:()=>dn,language_models__profile:()=>li,load__serializable:()=>u,memory:()=>br,messages:()=>at,messages__tool:()=>Oe,output_parsers:()=>Nt,output_parsers__openai_functions:()=>pi,output_parsers__openai_tools:()=>fn,outputs:()=>it,prompt_values:()=>$t,prompts:()=>Ca,retrievers:()=>kr,retrievers__document_compressors:()=>wa,runnables:()=>Kt,runnables__graph:()=>De,singletons:()=>me,stores:()=>Er,structured_query:()=>Ua,tools:()=>an,tracers__base:()=>Be,tracers__console:()=>Ue,tracers__log_stream:()=>Ae,tracers__run_collector:()=>Wa,tracers__tracer_langchain:()=>se,types__stream:()=>Ka,utils__async_caller:()=>tt,utils__chunk_array:()=>un,utils__context:()=>qa,utils__env:()=>y,utils__event_source_parse:()=>Za,utils__format:()=>so,utils__function_calling:()=>Yt,utils__hash:()=>Wt,utils__json_patch:()=>Rt,utils__json_schema:()=>ht,utils__math:()=>po,utils__stream:()=>Ye,utils__testing:()=>Ro,utils__tiktoken:()=>Jt,utils__types:()=>Lt,vectorstores:()=>jr});var Bo=50;function Vo(e){let t={};for(let n=e;n&&n.prototype;n=Object.getPrototypeOf(n))Object.assign(t,Reflect.get(n.prototype,`lc_aliases`));return Object.entries(t).reduce((e,[t,n])=>(e[n]=t,e),{})}async function Ho(e){let{optionalImportsMap:t,optionalImportEntrypoints:n,importMap:r,secretsMap:a,secretsFromEnv:o,path:s,depth:c,maxDepth:l}=this,u=s.join(`.`);if(c>l)throw Error(`Maximum recursion depth (${l}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`);if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return Promise.all(e.map((e,t)=>Ho.call({...this,path:[...s,`${t}`],depth:c+1},e)));let d=e;if(oe(d))return He(d);if(`lc`in d&&`type`in d&&`id`in d&&d.lc===1&&d.type===`secret`){let[e]=d.id;if(e in a)return a[e];if(o){let t=Se(e);if(t)return t}throw Error(`Missing secret "${e}" at ${u}`)}if(`lc`in d&&`type`in d&&`id`in d&&d.lc===1&&d.type===`not_implemented`){let e=JSON.stringify(d);throw Error(`Trying to load an object that doesn't implement serialization: ${u} -> ${e}`)}if(`lc`in d&&`type`in d&&`id`in d&&`kwargs`in d&&d.lc===1&&d.type===`constructor`){let e=d,a=JSON.stringify(e),[o,...l]=e.id.slice().reverse(),p=l.reverse(),m={langchain_core:zo,langchain:r},h=null,g=[p.join(`/`)];p[0]===`langchain_community`&&g.push([`langchain`,...p.slice(1)].join(`/`));let _=g.find(e=>e in t);if(pr.concat(n).includes(p.join(`/`))||_)if(_!==void 0)h=await t[_];else throw Error(`Missing key "${p.join(`/`)}" for ${u} in load(optionalImportsMap={})`);else{let e;if(p[0]===`langchain`||p[0]===`langchain_core`)e=m[p[0]],p.shift();else throw Error(`Invalid namespace: ${u} -> ${a}`);if(p.length===0)throw Error(`Invalid namespace: ${u} -> ${a}`);let t;do{if(t=p.join(`__`),t in e)break;p.pop()}while(p.length>0);t in e&&(h=e[t])}if(typeof h!=`object`||!h)throw Error(`Invalid namespace: ${u} -> ${a}`);let v=h[o]??Object.values(h).find(e=>typeof e==`function`&&f(e)===o);if(typeof v!=`function`)throw Error(`Invalid identifer: ${u} -> ${a}`);let y=new v(ze(await Ho.call({...this,path:[...s,`kwargs`],depth:c+1},e.kwargs),i,Vo(v)));return Object.defineProperty(y.constructor,`name`,{value:o}),y}let p={};for(let[e,t]of Object.entries(d))p[e]=await Ho.call({...this,path:[...s,e],depth:c+1},t);return p}async function Uo(e,t){let n=JSON.parse(e),r={optionalImportsMap:t?.optionalImportsMap??{},optionalImportEntrypoints:t?.optionalImportEntrypoints??[],secretsMap:t?.secretsMap??{},secretsFromEnv:t?.secretsFromEnv??!1,importMap:t?.importMap??{},path:[`$`],depth:0,maxDepth:t?.maxDepth??Bo};return Ho.call(r,n)}function Wo(e){return e!==null&&e.lc===1&&e.type===`constructor`&&Array.isArray(e.id)}async function Go(e){if(e&&typeof e==`object`){if(Array.isArray(e))return await Promise.all(e.map(e=>Go(e)));{let t={};for(let[n,r]of Object.entries(e))t[n]=await Go(r);if(t.lc===2&&t.type===`undefined`)return;if(t.lc===2&&t.type===`constructor`&&Array.isArray(t.id))try{let e=t.id[t.id.length-1],n;switch(e){case`Set`:n=Set;break;case`Map`:n=Map;break;case`RegExp`:n=RegExp;break;case`Error`:n=Error;break;default:return t}return t.method?n[t.method](...t.args||[]):new n(...t.args||[])}catch{return t}else if(Wo(t))return Uo(JSON.stringify(t));return t}}return e}function Ko(e,t,n,r){return{lc:2,type:`constructor`,id:[e.name],method:t??null,args:n??[],kwargs:r??{}}}function qo(e){return e===void 0?{lc:2,type:`undefined`}:e instanceof Set||e instanceof Map?Ko(e.constructor,void 0,[Array.from(e)]):e instanceof RegExp?Ko(RegExp,void 0,[e.source,e.flags]):e instanceof Error?Ko(e.constructor,void 0,[e.message]):e?.lg_name===`Send`?{node:e.node,args:e.args}:e}var Jo=class{_dumps(e){return new TextEncoder().encode(lr(e,(e,t)=>qo(t)))}async dumpsTyped(e){return e instanceof Uint8Array?[`bytes`,e]:[`json`,this._dumps(e)]}async _loads(e){return Go(JSON.parse(e))}async loadsTyped(e,t){if(e===`bytes`)return typeof t==`string`?new TextEncoder().encode(t):t;if(e===`json`)return this._loads(typeof t==`string`?t:new TextDecoder().decode(t));throw Error(`Unknown serialization type: ${e}`)}};function Yo(e){if(typeof e!=`object`||!e)return e;let t=Array.isArray(e)?[]:{};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=Yo(e[n]));return t}function Xo(){return{v:4,id:Qn(-2),ts:new Date().toISOString(),channel_values:{},channel_versions:{},versions_seen:{}}}function Zo(e){return{v:e.v,id:e.id,ts:e.ts,channel_values:{...e.channel_values},channel_versions:{...e.channel_versions},versions_seen:Yo(e.versions_seen)}}function Qo(e,t){return typeof e==`number`&&typeof t==`number`?Math.sign(e-t):String(e).localeCompare(String(t))}function $o(...e){return e.reduce((e,t,n)=>n===0?t:Qo(e,t)>=0?e:t)}var es={[er]:-1,[tr]:-2,[nr]:-3,[rr]:-4},ts=class extends Error{constructor(e){super(e),this.name=`InvalidNamespaceError`}};function ns(e){if(e.length===0)throw new ts(`Namespace cannot be empty.`);for(let t of e){if(typeof t!=`string`)throw new ts(`Invalid namespace label '${t}' found in ${e}. Namespace labels must be strings, but got ${typeof t}.`);if(t.includes(`.`))throw new ts(`Invalid namespace label '${t}' found in ${e}. Namespace labels cannot contain periods ('.').`);if(t===``)throw new ts(`Namespace labels cannot be empty strings. Got ${t} in ${e}`)}if(e[0]===`langgraph`)throw new ts(`Root label for namespace cannot be "langgraph". Got: ${e}`)}var rs=class{async get(e,t){return(await this.batch([{namespace:e,key:t}]))[0]}async search(e,t={}){let{filter:n,limit:r=10,offset:i=0,query:a}=t;return(await this.batch([{namespacePrefix:e,filter:n,limit:r,offset:i,query:a}]))[0]}async put(e,t,n,r){ns(e),await this.batch([{namespace:e,key:t,value:n,index:r}])}async delete(e,t){await this.batch([{namespace:e,key:t,value:null}])}async listNamespaces(e={}){let{prefix:t,suffix:n,maxDepth:r,limit:i=100,offset:a=0}=e,o=[];return t&&o.push({matchType:`prefix`,path:t}),n&&o.push({matchType:`suffix`,path:n}),(await this.batch([{matchConditions:o.length?o:void 0,maxDepth:r,limit:i,offset:a}]))[0]}start(){}stop(){}},is=e=>`lg_name`in e&&e.lg_name===`AsyncBatchedStore`?e.store:e,as=class extends rs{lg_name=`AsyncBatchedStore`;store;queue=new Map;nextKey=0;running=!1;processingTask=null;constructor(e){super(),this.store=is(e)}get isRunning(){return this.running}async batch(e){throw Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong.")}async get(e,t){return this.enqueueOperation({namespace:e,key:t})}async search(e,t){let{filter:n,limit:r=10,offset:i=0,query:a}=t||{};return this.enqueueOperation({namespacePrefix:e,filter:n,limit:r,offset:i,query:a})}async put(e,t,n){return this.enqueueOperation({namespace:e,key:t,value:n})}async delete(e,t){return this.enqueueOperation({namespace:e,key:t,value:null})}start(){this.running||(this.running=!0,this.processingTask=this.processBatchQueue())}async stop(){this.running=!1,this.processingTask&&await this.processingTask}enqueueOperation(e){return new Promise((t,n)=>{let r=this.nextKey;this.nextKey+=1,this.queue.set(r,{operation:e,resolve:t,reject:n})})}async processBatchQueue(){for(;this.running;){if(await new Promise(e=>{setTimeout(e,0)}),this.queue.size===0)continue;let e=new Map(this.queue);this.queue.clear();try{let t=Array.from(e.values()).map(({operation:e})=>e),n=await this.store.batch(t);e.forEach(({resolve:t},r)=>{t(n[Array.from(e.keys()).indexOf(r)])})}catch(t){e.forEach(({reject:e})=>{e(t)})}}}toJSON(){return{queue:this.queue,nextKey:this.nextKey,running:this.running,store:`[LangGraphStore]`}}},os=class{serde=new Jo;constructor(e){this.serde=e||this.serde}};function ss(e){return e!=null&&e.lg_is_channel===!0}var cs=class{ValueType;UpdateType;lg_is_channel=!0;consume(){return!1}finish(){return!1}isAvailable(){try{return this.get(),!0}catch(e){if(e.name===N.unminifiable_name)return!1;throw e}}equals(e){return this===e}},ls=Symbol.for(`LG_IS_ONLY_BASE_CHANNEL`);function us(e){if(e[ls]===!0)return e;let t={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let r=e[n];ss(r)&&(t[n]=r)}return Object.assign(t,{[ls]:!0}),t}function ds(e,t){let n=us(e),r={};for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;let i=t.channel_values[e];r[e]=n[e].fromCheckpoint(i)}return Object.assign(r,{[ls]:!0}),r}function fs(e,t,n,r){let i;if(t===void 0)i=e.channel_values;else{i={};for(let e in t)if(Object.prototype.hasOwnProperty.call(t,e))try{i[e]=t[e].checkpoint()}catch(e){if(e.name!==N.unminifiable_name)throw e}}return{v:4,id:r?.id??Qn(n),ts:new Date().toISOString(),channel_values:i,channel_versions:e.channel_versions,versions_seen:e.versions_seen}}var ps=e=>e!=null&&e.lc_graph_name===`BinaryOperatorAggregate`,ms=class e extends cs{lc_graph_name=`BinaryOperatorAggregate`;value;operator;initialValueFactory;constructor(e,t){super(),this.operator=e,this.initialValueFactory=t,this.value=t?.()}fromCheckpoint(t){let n=new e(this.operator,this.initialValueFactory);return t!==void 0&&(n.value=t),n}update(e){let t=e;if(!t.length)return!1;this.value===void 0&&([this.value]=t,t=t.slice(1));for(let e of t)this.value!==void 0&&(this.value=this.operator(this.value,e));return!0}get(){if(this.value===void 0)throw new N;return this.value}checkpoint(){if(this.value===void 0)throw new N;return this.value}isAvailable(){return this.value!==void 0}equals(e){return this===e?!0:ps(e)?this.operator===e.operator:!1}},hs=class e extends cs{lc_graph_name=`LastValue`;value=[];constructor(e){super(),this.initialValueFactory=e,e&&(this.value=[e()])}fromCheckpoint(t){let n=new e(this.initialValueFactory);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0)return!1;if(e.length!==1)throw new P(`LastValue can only receive one value per step.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new N;return this.value[0]}checkpoint(){if(this.value.length===0)throw new N;return this.value[0]}isAvailable(){return this.value.length!==0}},gs=class e extends cs{lc_graph_name=`LastValueAfterFinish`;value=[];finished=!1;fromCheckpoint(t){let n=new e;if(t!==void 0){let[e,r]=t;n.value=[e],n.finished=r}return n}update(e){return e.length===0?!1:(this.finished=!1,this.value=[e[e.length-1]],!0)}get(){if(this.value.length===0||!this.finished)throw new N;return this.value[0]}checkpoint(){if(this.value.length!==0)return[this.value[0],this.finished]}consume(){return this.finished?(this.finished=!1,this.value=[],!0):!1}finish(){return!this.finished&&this.value.length>0?(this.finished=!0,!0):!1}isAvailable(){return this.value.length!==0&&this.finished}},_s=class{lc_graph_name=`AnnotationRoot`;spec;constructor(e){this.spec=e}static isInstance(e){return typeof e==`object`&&!!e&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`}},vs=function(e){return e?ys(e):new hs};vs.Root=e=>new _s(e);function ys(e){return typeof e==`object`&&e&&`reducer`in e&&e.reducer?new ms(e.reducer,e.default):typeof e==`object`&&e&&`value`in e&&e.value?new ms(e.value,e.default):new hs}var R=`__start__`,z=`__end__`,bs=`__input__`,xs=`__error__`,Ss=`__pregel_ns_writes`,Cs=`__pregel_send`,ws=`__pregel_call`,Ts=`__pregel_read`,Es=`__pregel_checkpointer`,Ds=`__pregel_resuming`,Os=`__pregel_task_id`,ks=`__pregel_stream`,As=`__pregel_resume_value`,js=`__pregel_resume_map`,Ms=`__pregel_scratchpad`,Ns=`__pregel_previous`,Ps=`__pregel_durability`,Fs=`checkpoint_id`,Is=`checkpoint_ns`,Ls=`__pregel_node_finished`,Rs=`checkpoint_map`,zs=`__pregel_abort_signals`,B=`__interrupt__`,Bs=`__resume__`,Vs=`__no_writes__`,Hs=`__return__`,Us=`__previous__`,V=`langsmith:hidden`,Ws=`__self__`,Gs=`__pregel_tasks`,Ks=`__pregel_push`,qs=`__pregel_pull`,Js=`00000000-0000-0000-0000-000000000000`,Ys=[V,bs,B,Bs,xs,Vs,Cs,Ts,Es,Ps,ks,Ds,Os,ws,As,Ms,Ns,Rs,Is,Fs],Xs=Symbol.for(`langgraph.command`),Zs=class{[Xs];constructor(e){this[Xs]=e}};function Qs(e){let t=e;return t!=null&&typeof t.node==`string`&&t.args!==void 0}var H=class{lg_name=`Send`;node;args;constructor(e,t){this.node=e,this.args=ec(t)}toJSON(){return{lg_name:this.lg_name,node:this.node,args:this.args}}};function U(e){return e instanceof H}function $s(e){return!e||typeof e!=`object`||!(`__interrupt__`in e)?!1:Array.isArray(e[B])}var W=class extends Zs{lg_name=`Command`;lc_direct_tool_output=!0;graph;update;resume;goto=[];static PARENT=`__parent__`;constructor(e){super(e),this.resume=e.resume,this.graph=e.graph,this.update=e.update,e.goto&&(this.goto=Array.isArray(e.goto)?ec(e.goto):[ec(e.goto)])}_updateAsTuples(){return this.update&&typeof this.update==`object`&&!Array.isArray(this.update)?Object.entries(this.update):Array.isArray(this.update)&&this.update.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`)?this.update:[[`__root__`,this.update]]}toJSON(){let e;return e=typeof this.goto==`string`?this.goto:U(this.goto)?this.goto.toJSON():this.goto?.map(e=>typeof e==`string`?e:e.toJSON()),{lg_name:this.lg_name,update:this.update,resume:this.resume,goto:e}}};function G(e){return typeof e!=`object`||!e?!1:`lg_name`in e&&e.lg_name===`Command`}function ec(e,t=new Map){if(typeof e==`object`&&e){if(t.has(e))return t.get(e);let n;if(Array.isArray(e))n=[],t.set(e,n),e.forEach((e,r)=>{n[r]=ec(e,t)});else if(G(e)&&!(e instanceof W))n=new W(e),t.set(e,n);else if(Qs(e)&&!(e instanceof H))n=new H(e.node,e.args),t.set(e,n);else if(G(e)||U(e))n=e,t.set(e,n);else if(`lc_serializable`in e&&e.lc_serializable)n=e,t.set(e,n);else{n={},t.set(e,n);for(let[r,i]of Object.entries(e))n[r]=ec(i,t)}return n}return e}var tc=[`tags`,`metadata`,`callbacks`,`configurable`],nc=[`tags`,`metadata`,`callbacks`,`runName`,`maxConcurrency`,`recursionLimit`,`configurable`,`runId`,`outputKeys`,`streamMode`,`store`,`writer`,`interrupt`,`context`,`interruptBefore`,`interruptAfter`,`checkpointDuring`,`durability`,`signal`],rc=25;function ic(...e){let t={tags:[],metadata:{},callbacks:void 0,recursionLimit:rc,configurable:{}},n=c.getRunnableConfig();if(n!==void 0){for(let[e,r]of Object.entries(n))if(r!==void 0)if(tc.includes(e)){let n;n=Array.isArray(r)?[...r]:typeof r==`object`?e===`callbacks`&&`copy`in r&&typeof r.copy==`function`?r.copy():{...r}:r,t[e]=n}else t[e]=r}for(let n of e)if(n!==void 0)for(let[e,r]of Object.entries(n))r!==void 0&&nc.includes(e)&&(t[e]=r);for(let[e,n]of Object.entries(t.configurable))t.metadata=t.metadata??{},!e.startsWith(`__`)&&(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)&&!(e in t.metadata)&&(t.metadata[e]=n);return t}function ac(){return c.getRunnableConfig()}function oc(e){return e.split(`|`).filter(e=>!e.match(/^\d+$/)).map(e=>e.split(`:`)[0]).join(`|`)}function sc(e){let t=e.split(`|`);for(;t.length>1&&t[t.length-1].match(/^\d+$/);)t.pop();return t.slice(0,-1).join(`|`)}var K=e=>BigInt(e),q=(e,t=0)=>new DataView(e.buffer,e.byteOffset+t,e.byteLength-t),cc=K(`0x9E3779B1`),lc=K(`0x85EBCA77`),uc=K(`0xC2B2AE3D`),dc=K(`0x9E3779B185EBCA87`),fc=K(`0xC2B2AE3D27D4EB4F`),pc=K(`0x165667B19E3779F9`),mc=K(`0x85EBCA77C2B2AE63`),hc=K(`0x27D4EB2F165667C5`),gc=K(`0x165667919E3779F9`),_c=K(`0x9FB21C651E98DF25`),vc=(e=>{let t=e.length;if(t%2!=0)throw Error(`String should have an even number of characters`);let n=t/2,r=new Uint8Array(n),i=0,a=0;for(;a<n;){let t=e.slice(i,i+=2);r[a]=Number.parseInt(t,16),a+=1}return q(r)})(`b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e`),yc=(K(1)<<K(128))-K(1),J=(K(1)<<K(64))-K(1),bc=(K(1)<<K(32))-K(1),xc=64,Sc=xc/8,Cc=8,wc=4;function Tc(e){if(!e)throw Error(`Assert failed`)}function Ec(e){let t=new DataView(new ArrayBuffer(8));return t.setBigUint64(0,e,!0),t.getBigUint64(0,!1)}function Dc(e){let t=e;return t=(t&K(65535))<<K(16)|(t&K(4294901760))>>K(16),t=(t&K(16711935))<<K(8)|(t&K(4278255360))>>K(8),t}function Oc(e,t){return(e&bc)*(t&bc)&J}function kc(e,t){return(e<<t|e>>K(32)-t)&bc}function Ac(e,t,n){for(let r=0;r<Sc;r+=1){let i=t.getBigUint64(r*8,!0),a=i^n.getBigUint64(r*8,!0);e[r^1]+=i,e[r]+=Oc(a,a>>K(32))}return e}function jc(e,t,n,r){for(let i=0;i<r;i+=1)Ac(e,q(t,i*xc),q(n,i*8));return e}function Mc(e,t){for(let n=0;n<Sc;n+=1){let r=t.getBigUint64(n*8,!0),i=e[n];i=Uc(i,K(47)),i^=r,i*=cc,e[n]=i&J}return e}function Nc(e,t){return Lc(e[0]^t.getBigUint64(0,!0),e[1]^t.getBigUint64(Cc,!0))}function Pc(e,t,n){let r=n;return r+=Nc(e.slice(0),q(t,0*wc)),r+=Nc(e.slice(2),q(t,4*wc)),r+=Nc(e.slice(4),q(t,8*wc)),r+=Nc(e.slice(6),q(t,12*wc)),Bc(r&J)}function Fc(e,t,n,r,i){let a=e,o=Math.floor((n.byteLength-xc)/8),s=xc*o,c=Math.floor((t.byteLength-1)/s);for(let e=0;e<c;e+=1)a=jc(a,q(t,e*s),n,o),a=i(a,q(n,n.byteLength-xc));{let e=Math.floor((t.byteLength-1-s*c)/xc);a=jc(a,q(t,c*s),n,e),a=r(a,q(t,t.byteLength-xc),q(n,n.byteLength-xc-7))}return a}function Ic(e,t){let n=new BigUint64Array([uc,dc,fc,pc,mc,lc,hc,cc]);Tc(e.byteLength>128),n=Fc(n,e,t,Ac,Mc),Tc(n.length*8==64);{let r=Pc(n,q(t,11),K(e.byteLength)*dc&J);return Pc(n,q(t,t.byteLength-xc-11),~(K(e.byteLength)*fc)&J)<<K(64)|r}}function Lc(e,t){let n=e*t&yc;return n&J^n>>K(64)}function Rc(e,t,n){return Lc((e.getBigUint64(0,!0)^t.getBigUint64(0,!0)+n)&J,(e.getBigUint64(8,!0)^t.getBigUint64(8,!0)-n)&J)}function zc(e,t,n,r,i){let a=e&J,o=e>>K(64)&J;return a+=Rc(t,r,i),a^=n.getBigUint64(0,!0)+n.getBigUint64(8,!0),a&=J,o+=Rc(n,q(r,16),i),o^=t.getBigUint64(0,!0)+t.getBigUint64(8,!0),o&=J,o<<K(64)|a}function Bc(e){let t=e;return t^=t>>K(37),t*=gc,t&=J,t^=t>>K(32),t}function Vc(e){let t=e;return t^=t>>K(33),t*=fc,t&=J,t^=t>>K(29),t*=pc,t&=J,t^=t>>K(32),t}function Hc(e,t,n){let r=e.byteLength;Tc(r>0&&r<=3);let i=K(e.getUint8(r-1))|K(r<<8)|K(e.getUint8(0)<<16)|K(e.getUint8(r>>1)<<24),a=(i^(K(t.getUint32(0,!0))^K(t.getUint32(4,!0)))+n)&J,o=(K(t.getUint32(8,!0))^K(t.getUint32(12,!0)))-n;return(Vc((kc(Dc(i),K(13))^o)&J)&J)<<K(64)|Vc(a)}function Uc(e,t){return e^e>>t}function Wc(e,t,n){let r=e.byteLength;Tc(r>=4&&r<=8);{let i=e.getUint32(0,!0),a=e.getUint32(r-4,!0),o=((K(i)|K(a)<<K(32))^(t.getBigUint64(16,!0)^t.getBigUint64(24,!0))+n&J)*(dc+(K(r)<<K(2)))&yc;return o+=(o&J)<<K(65),o&=yc,o^=o>>K(67),Uc(Uc(o&J,K(35))*_c&J,K(28))|Bc(o>>K(64))<<K(64)}}function Gc(e,t,n){let r=e.byteLength;Tc(r>=9&&r<=16);{let i=(t.getBigUint64(32,!0)^t.getBigUint64(40,!0))+n&J,a=(t.getBigUint64(48,!0)^t.getBigUint64(56,!0))-n&J,o=e.getBigUint64(0,!0),s=e.getBigUint64(r-8,!0),c=(o^s^i)*dc,l=(c&J)+(K(r-1)<<K(54));c=c&(yc^J)|l,s^=a,c+=s+(s&bc)*(lc-K(1))<<K(64),c&=yc,c^=Ec(c>>K(64));let u=(c&J)*fc;return u+=(c>>K(64))*fc<<K(64),u&=yc,Bc(u&J)|Bc(u>>K(64))<<K(64)}}function Kc(e,t){let n=e.byteLength;return Tc(n<=16),n>8?Gc(e,vc,t):n>=4?Wc(e,vc,t):n>0?Hc(e,vc,t):Vc(t^vc.getBigUint64(64,!0)^vc.getBigUint64(72,!0))|Vc(t^vc.getBigUint64(80,!0)^vc.getBigUint64(88,!0))<<K(64)}function qc(e){return~e+K(1)&J}function Jc(e,t,n){let r=K(e.byteLength)*dc&J,i=K(e.byteLength-1)/K(32);for(;i>=0;){let a=Number(i);r=zc(r,q(e,16*a),q(e,e.byteLength-16*(a+1)),q(t,32*a),n),i-=K(1)}let a=r+(r>>K(64))&J;a=Bc(a);let o=(r&J)*dc+(r>>K(64))*mc+(K(e.byteLength)-n&J)*fc;return o&=J,o=qc(Bc(o)),a|o<<K(64)}function Yc(e,t,n){let r=K(e.byteLength)*dc&J;for(let i=32;i<160;i+=32)r=zc(r,q(e,i-32),q(e,i-16),q(t,i-32),n);r=Bc(r&J)|Bc(r>>K(64))<<K(64);for(let i=160;i<=e.byteLength;i+=32)r=zc(r,q(e,i-32),q(e,i-16),q(t,3+i-160),n);r=zc(r,q(e,e.byteLength-16),q(e,e.byteLength-32),q(t,103),qc(n));let i=r+(r>>K(64))&J;i=Bc(i);let a=(r&J)*dc+(r>>K(64))*mc+(K(e.byteLength)-n&J)*fc;return a&=J,a=qc(Bc(a)),i|a<<K(64)}function Xc(e,t=K(0)){let n=new TextEncoder,r=q(typeof e==`string`?n.encode(e):e),i=r.byteLength;return(e=>e.toString(16).padStart(32,`0`))(i<=16?Kc(r,t):i<=128?Jc(r,vc,t):i<=240?Yc(r,vc,t):Ic(r,vc))}function Zc(e){return/^[0-9a-f]{32}$/.test(e)}function Qc(e){let t=c.getRunnableConfig();if(!t)throw Error(`Called interrupt() outside the context of a graph.`);let n=t.configurable;if(!n)throw Error(`No configurable found in config`);if(!n.__pregel_checkpointer)throw new Hn(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=n[Ms];r.interruptCounter+=1;let i=r.interruptCounter;if(r.resume.length>0&&i<r.resume.length)return n[Cs]?.([[Bs,r.resume]]),r.resume[i];if(r.nullResume!==void 0){if(r.resume.length!==i)throw Error(`Resume length mismatch: ${r.resume.length} !== ${i}`);let e=r.consumeNullResume();return r.resume.push(e),n[Cs]?.([[Bs,r.resume]]),e}let a=n[Is]?.split(`|`);throw new Un([{id:a?Xc(a.join(`|`)):void 0,value:e}])}var $c=class extends E{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.trace=e.trace??this.trace,this.recurse=e.recurse??this.recurse}async _tracedInvoke(e,t,n){return new Promise((r,i)=>{let a=ke(t,{callbacks:n?.getChild()});c.runWithConfig(a,async()=>{try{r(await this.func(e,a))}catch(e){i(e)}})})}async invoke(e,t){let n,r=ic(t),i=bt(this.config,r);return n=this.trace?await this._callWithConfig(this._tracedInvoke,e,i):await c.runWithConfig(i,async()=>this.func(e,i)),E.isRunnable(n)&&this.recurse?await c.runWithConfig(i,async()=>n.invoke(e,i)):n}};function*el(e,t){if(t===void 0)yield*e;else for(let n of e)yield[t,n]}async function tl(e){let t=[];for await(let n of await e)t.push(n);return t}function nl(e){let t=[];for(let n of e)t.push(n);return t}function rl(e,t){return e?`configurable`in e?{...e,configurable:{...e.configurable,...t}}:{...e,configurable:t}:{configurable:t}}function il(e){return e!=null&&typeof e==`function`&&e instanceof Object.getPrototypeOf(async function*(){}).constructor}function al(e){return e!=null&&typeof e==`function`&&e instanceof Object.getPrototypeOf(function*(){}).constructor}function ol(e){return typeof e==`object`&&e?.[Symbol.for(`LG_SKIP_WRITE`)]!==void 0}var sl={[Symbol.for(`LG_PASSTHROUGH`)]:!0};function cl(e){return typeof e==`object`&&e?.[Symbol.for(`LG_PASSTHROUGH`)]!==void 0}var ll=Symbol(`IS_WRITER`),Y=class e extends $c{writes;constructor(e,t){let n=`ChannelWrite<${e.map(e=>U(e)?e.node:`channel`in e?e.channel:`...`).join(`,`)}>`;super({writes:e,name:n,tags:t,func:async(e,t)=>this._write(e,t??{})}),this.writes=e}async _write(t,n){let r=this.writes.map(e=>dl(e)&&cl(e.value)?{mapper:e.mapper,value:t}:ul(e)&&cl(e.value)?{channel:e.channel,value:t,skipNone:e.skipNone,mapper:e.mapper}:e);return await e.doWrite(n,r),t}static async doWrite(e,t){for(let e of t){if(ul(e)){if(e.channel===`__pregel_tasks`)throw new P(`Cannot write to the reserved channel TASKS`);if(cl(e.value))throw new P(`PASSTHROUGH value must be replaced`)}if(dl(e)&&cl(e.value))throw new P(`PASSTHROUGH value must be replaced`)}let n=[];for(let r of t)if(U(r))n.push([Gs,r]);else if(dl(r)){let t=await r.mapper.invoke(r.value,e);t!=null&&t.length>0&&n.push(...t)}else if(ul(r)){let t=r.mapper===void 0?r.value:await r.mapper.invoke(r.value,e);if(ol(t)||r.skipNone&&t===void 0)continue;n.push([r.channel,t])}else throw Error(`Invalid write entry: ${JSON.stringify(r)}`);let r=e.configurable?.[Cs];r(n)}static isWriter(t){return t instanceof e||ll in t&&!!t[ll]}static registerWriter(e){return Object.defineProperty(e,ll,{value:!0})}};function ul(e){return e!==void 0&&typeof e.channel==`string`}function dl(e){return e!==void 0&&!ul(e)&&E.isRunnable(e.mapper)}var fl=class e extends $c{lc_graph_name=`ChannelRead`;channel;fresh=!1;mapper;constructor(t,n,r=!1){super({func:(t,n)=>e.doRead(n,this.channel,this.fresh,this.mapper)}),this.fresh=r,this.mapper=n,this.channel=t,this.name=Array.isArray(t)?`ChannelRead<${t.join(`,`)}>`:`ChannelRead<${t}>`}static doRead(e,t,n,r){let i=e.configurable?.[Ts];if(!i)throw Error(`Runnable is not configured with a read function. Make sure to call in the context of a Pregel process`);return r?r(i(t,n)):i(t,n)}},pl=new Ft,ml=class e extends nt{lc_graph_name=`PregelNode`;channels;triggers=[];mapper;writers=[];bound=pl;kwargs={};metadata={};tags=[];retryPolicy;cachePolicy;subgraphs;ends;constructor(e){let{channels:t,triggers:n,mapper:r,writers:i,bound:a,kwargs:o,metadata:s,retryPolicy:c,cachePolicy:l,tags:u,subgraphs:d,ends:f}=e,p=[...e.config?.tags?e.config.tags:[],...u??[]];super({...e,bound:e.bound??pl,config:{...e.config?e.config:{},tags:p}}),this.channels=t,this.triggers=n,this.mapper=r,this.writers=i??this.writers,this.bound=a??this.bound,this.kwargs=o??this.kwargs,this.metadata=s??this.metadata,this.tags=p,this.retryPolicy=c,this.cachePolicy=l,this.subgraphs=d,this.ends=f}getWriters(){let e=[...this.writers];for(;e.length>1&&e[e.length-1]instanceof Y&&e[e.length-2]instanceof Y;){let t=e.slice(-2),n=t[0].writes.concat(t[1].writes);e[e.length-2]=new Y(n,t[0].config?.tags),e.pop()}return e}getNode(){let e=this.getWriters();if(!(this.bound===pl&&e.length===0))return this.bound===pl&&e.length===1?e[0]:this.bound===pl?new qe({first:e[0],middle:e.slice(1,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):e.length>0?new qe({first:this.bound,middle:e.slice(0,e.length-1),last:e[e.length-1],omitSequenceTags:!0}):this.bound}join(t){if(!Array.isArray(t))throw Error(`channels must be a list`);if(typeof this.channels!=`object`)throw Error(`all channels must be named when using .join()`);return new e({channels:{...this.channels,...Object.fromEntries(t.map(e=>[e,e]))},triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound,kwargs:this.kwargs,config:this.config,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}pipe(t){return Y.isWriter(t)?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:[...this.writers,t],bound:this.bound,config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):this.bound===pl?new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:ut(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy}):new e({channels:this.channels,triggers:this.triggers,mapper:this.mapper,writers:this.writers,bound:this.bound.pipe(t),config:this.config,kwargs:this.kwargs,retryPolicy:this.retryPolicy,cachePolicy:this.cachePolicy})}};function hl(e){return`steps`in e&&Array.isArray(e.steps)}function gl(e){return`lg_is_pregel`in e&&e.lg_is_pregel===!0}function _l(e){let t=[e];for(let e of t)if(gl(e))return e;else hl(e)&&t.push(...e.steps)}function vl(e,t,n=!0,r=!1){try{return e[t].get()}catch(e){if(e.name===N.unminifiable_name){if(r)return e;if(n)return null}throw e}}function yl(e,t,n=!0){if(Array.isArray(t)){let r={};for(let i of t)try{r[i]=vl(e,i,!n)}catch(e){if(e.name===N.unminifiable_name)continue}return r}else return vl(e,t)}function*bl(e,t){if(e.graph===W.PARENT)throw new P(`There is no parent graph.`);if(e.goto){let t;t=Array.isArray(e.goto)?e.goto:[e.goto];for(let e of t)if(U(e))yield[Js,Gs,e];else if(typeof e==`string`)yield[Js,`branch:to:${e}`,`__start__`];else throw Error(`In Command.send, expected Send or string, got ${typeof e}`)}if(e.resume)if(typeof e.resume==`object`&&Object.keys(e.resume).length&&Object.keys(e.resume).every(Zc))for(let[n,r]of Object.entries(e.resume)){let e=t.filter(e=>e[0]===n&&e[1]===`__resume__`).map(e=>e[2]).slice(0,1)??[];e.push(r),yield[n,Bs,e]}else yield[Js,Bs,e.resume];if(e.update){if(typeof e.update!=`object`||!e.update)throw Error(`Expected cmd.update to be a dict mapping channel names to update values`);if(Array.isArray(e.update))for(let[t,n]of e.update)yield[Js,t,n];else for(let[t,n]of Object.entries(e.update))yield[Js,t,n]}}function*xl(e,t){if(t!=null)if(Array.isArray(e)&&typeof t==`object`&&!Array.isArray(t))for(let n in t)e.includes(n)&&(yield[n,t[n]]);else if(Array.isArray(e))throw Error(`Input chunk must be an object when "inputChannels" is an array`);else yield[e,t]}function*Sl(e,t,n){Array.isArray(e)?(t===!0||t.find(([t,n])=>e.includes(t)))&&(yield yl(n,e)):(t===!0||t.some(([t,n])=>t===e))&&(yield vl(n,e))}function*Cl(e,t,n){let r=t.filter(([e,t])=>(e.config===void 0||!e.config.tags?.includes(`langsmith:hidden`))&&t[0][0]!==`__error__`&&t[0][0]!==`__interrupt__`);if(!r.length)return;let i;i=r.some(([e])=>e.writes.some(([e,t])=>e===`__return__`))?r.flatMap(([e])=>e.writes.filter(([e,t])=>e===Hs).map(([t,n])=>[e.name,n])):Array.isArray(e)?r.flatMap(([t])=>{let{writes:n}=t,r={};for(let[t]of n)e.includes(t)&&(r[t]=(r[t]||0)+1);return Object.values(r).some(e=>e>1)?n.filter(([t])=>e.includes(t)).map(([e,n])=>[t.name,{[e]:n}]):[[t.name,Object.fromEntries(n.filter(([t])=>e.includes(t)))]]}):r.flatMap(([t])=>t.writes.filter(([t,n])=>t===e).map(([e,n])=>[t.name,n]));let a={};for(let[e,t]of i)e in a||(a[e]=[]),a[e].push(t);let o={};for(let e in a)if(a[e].length===1){let[t]=a[e];o[e]=t}else o[e]=a[e];n&&(o.__metadata__={cached:n}),yield o}function wl(e){let t=typeof e[R];if(t===`number`)return 0;if(t===`string`)return``;for(let t in e){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let n=typeof e[t];if(n===`number`)return 0;if(n===`string`)return``;break}}function Tl(e,t){if(Object.keys(e).length>0){let n=wl(t);return Object.fromEntries(Object.entries(t).filter(([t,r])=>r>(e[t]??n)))}else return t}function El(e,t){return e&&!Array.isArray(e)&&!(e instanceof Date)&&typeof e==`object`?e:{[t]:e}}function Dl(e,t){return e===null?{configurable:t}:e?.configurable===void 0?{...e,configurable:t}:{...e,configurable:{...e.configurable,...t}}}function Ol(e,t){let n=t?.parents??{};return Object.keys(n).length>0?Dl(e,{[Rs]:{...n,[e.configurable?.checkpoint_ns??``]:e.configurable?.checkpoint_id}}):e}function kl(...e){let t=[...new Set(e.filter(Boolean))];if(t.length===0)return{signal:void 0,dispose:void 0};if(t.length===1)return{signal:t[0],dispose:void 0};let n=new AbortController,r=()=>{let e=t.find(e=>e.aborted)?.reason;n.abort(e),t.forEach(e=>e.removeEventListener(`abort`,r))};t.forEach(e=>e.addEventListener(`abort`,r,{once:!0}));let i=t.find(e=>e.aborted);return i&&n.abort(i.reason),{signal:n.signal,dispose:()=>{t.forEach(e=>e.removeEventListener(`abort`,r))}}}var Al=(e,t)=>{if(!(!e&&!t))return e?t?Array.isArray(e)&&Array.isArray(t)?[...e,...t]:Array.isArray(e)?[...e,t]:Array.isArray(t)?[e,...t]:[e,t]:e:t},jl=class{func;name;input;retry;cache;callbacks;__lg_type=`call`;constructor({func:e,name:t,input:n,retry:r,cache:i,callbacks:a}){this.func=e,this.name=t,this.input=n,this.retry=r,this.cache=i,this.callbacks=a}};function Ml(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`call`}function Nl(e,t){return new qe({name:e,first:new $c({func:e=>t(...e),name:e,trace:!1,recurse:!1}),last:new Y([{channel:Hs,value:sl}],[V])})}function Pl(e,t){return new $c({func:(e,n)=>t(e,n),name:e,trace:!1,recurse:!1})}var Fl=e=>e===void 0?1:e+1;function Il(e,t){if(t==null)return!1;for(let n of e)if(t[n])return!0;return!1}function Ll(e){let t;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t=t==null?e[n]:$o(t,e[n]));return t}function Rl(e,t,n){let r=wl(e.channel_versions),i=e.versions_seen.__interrupt__??{},a=!1;if((e.channel_versions.__start__??r)>(i.__start__??r))a=!0;else for(let t in e.channel_versions)if(Object.prototype.hasOwnProperty.call(e.channel_versions,t)&&e.channel_versions[t]>(i[t]??r)){a=!0;break}let o=n.some(e=>t===`*`?!e.config?.tags?.includes(V):t.includes(e.name));return a&&o}function zl(e,t,n,r,i=!1){let a=new Set;if(Array.isArray(r))a=new Set(r.filter(e=>n.writes.some(([t,n])=>t===e)));else{for(let[e]of n.writes)if(e===r){a=new Set([e]);break}a||=new Set}let o;if(i&&a.size>0){let i=Object.fromEntries(Object.entries(t).filter(([e,t])=>a.has(e))),s=fs(e,i,-1),c=ds(i,s);Hl(Zo(s),c,[n],void 0,void 0),o=yl({...t,...c},r)}else o=yl(t,r);return o}function Bl(e,t,n){for(let[e,r]of n)if([`__pregel_push`,`__pregel_tasks`].includes(e)&&r!=null){if(!U(r))throw new P(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(r)}`);if(!(r.node in t))throw new P(`Invalid node name "${r.node}" in Send packet`)}e(n)}var Vl=new Set([Vs,Ks,Bs,B,Hs,xs]);function Hl(e,t,n,r,i){n.sort((e,t)=>{let n=e.path?.slice(0,3)||[],r=t.path?.slice(0,3)||[];for(let e=0;e<Math.min(n.length,r.length);e+=1){if(n[e]<r[e])return-1;if(n[e]>r[e])return 1}return n.length-r.length});let a=n.some(e=>e.triggers.length>0),o=us(t);for(let t of n){e.versions_seen[t.name]??={};for(let n of t.triggers)n in e.channel_versions&&(e.versions_seen[t.name][n]=e.channel_versions[n])}let s=Ll(e.channel_versions),c=new Set(n.flatMap(e=>e.triggers).filter(e=>!Ys.includes(e))),l=!1;for(let t of c)t in o&&o[t].consume()&&r!==void 0&&(e.channel_versions[t]=r(s),l=!0);let u={};for(let e of n)for(let[t,n]of e.writes)Vl.has(t)||t in o&&(u[t]??=[],u[t].push(n));s!=null&&r!=null&&(s=l?r(s):s);let d=new Set;for(let[t,n]of Object.entries(u))if(t in o){let i=o[t],a;try{a=i.update(n)}catch(e){if(e.name===P.unminifiable_name){let r=new P(`Invalid update for channel "${t}" with values ${JSON.stringify(n)}: ${e.message}`);throw r.lc_error_code=e.lc_error_code,r}else throw e}a&&r!==void 0&&(e.channel_versions[t]=r(s),i.isAvailable()&&d.add(t))}if(a)for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.isAvailable()&&!d.has(t)&&n.update([])&&r!==void 0&&(e.channel_versions[t]=r(s),n.isAvailable()&&d.add(t))}if(a&&!Il(d,i))for(let t in o){if(!Object.prototype.hasOwnProperty.call(o,t))continue;let n=o[t];n.finish()&&r!==void 0&&(e.channel_versions[t]=r(s),n.isAvailable()&&d.add(t))}return d}function*Ul(e,t,n){if(n.updatedChannels!=null&&n.triggerToNodes!=null){let e=new Set;for(let t of n.updatedChannels){let r=n.triggerToNodes[t];for(let t of r??[])e.add(t)}yield*[...e].sort();return}if(!(()=>{for(let t in e.channel_versions)if(e.channel_versions[t]!==null)return!1;return!0})())for(let e in t)Object.prototype.hasOwnProperty.call(t,e)&&(yield e)}function Wl(e,t,n,r,i,a,o){let s={},c=r[Gs];if(c?.isAvailable()){let l=c.get().length;for(let c=0;c<l;c+=1){let l=Gl([Ks,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}}for(let c of Ul(e,n,o)){let l=Gl([qs,c],e,t,n,r,i,a,o);l!==void 0&&(s[l.id]=l)}return s}function Gl(e,t,n,r,i,a,o,s){let{step:c,checkpointer:l,manager:u}=s,d=a.configurable??{},f=d.checkpoint_ns??``;if(e[0]===`__pregel_push`&&Ml(e[e.length-1])){let p=e[e.length-1],m=Nl(p.name,p.func),h=[Ks],g=f===``?p.name:`${f}|${p.name}`,_=$n(JSON.stringify([g,c.toString(),p.name,Ks,e[1],e[2]]),t.id),v=`${g}:${_}`,y=[...e.slice(0,3),!0],b={langgraph_step:c,langgraph_node:p.name,langgraph_triggers:h,langgraph_path:y,langgraph_checkpoint_ns:v};if(o){let e=[];return{name:p.name,input:p.input,proc:m,writes:e,config:ke(bt(a,{metadata:b,store:s.store??a.store}),{runName:p.name,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Os]:_,[Cs]:t=>Bl(t=>e.push(...t),r,t),[Ts]:(n,r=!1)=>zl(t,i,{name:p.name,writes:e,triggers:h,path:y},n,r),[Es]:l??d.__pregel_checkpointer,[Rs]:{...d[Rs],[f]:t.id},[Ms]:Jl({pendingWrites:n??[],taskId:_,currentTaskInput:p.input,resumeMap:a.configurable?.[js],namespaceHash:Xc(v)}),[Ns]:t.channel_values[Us],checkpoint_id:void 0,checkpoint_ns:v}}),triggers:h,retry_policy:p.retry,cache_key:p.cache?{key:Xc((p.cache.keyFunc??JSON.stringify)([p.input])),ns:[Ss,p.name??`__dynamic__`],ttl:p.cache.ttl}:void 0,id:_,path:y,writers:[]}}else return{id:_,name:p.name,interrupts:[],path:y}}else if(e[0]===`__pregel_push`){let p=typeof e[1]==`number`?e[1]:parseInt(e[1],10);if(!i.__pregel_tasks?.isAvailable())return;let m=i[Gs].get();if(p<0||p>=m.length)return;let h=Qs(m[p])&&!U(m[p])?new H(m[p].node,m[p].args):m[p];if(!Qs(h)){console.warn(`Ignoring invalid packet ${JSON.stringify(h)} in pending sends.`);return}if(!(h.node in r)){console.warn(`Ignoring unknown node name ${h.node} in pending sends.`);return}let g=[Ks],_=f===``?h.node:`${f}|${h.node}`,v=$n(JSON.stringify([_,c.toString(),h.node,Ks,p.toString()]),t.id),y=`${_}:${v}`,b={langgraph_step:c,langgraph_node:h.node,langgraph_triggers:g,langgraph_path:e.slice(0,3),langgraph_checkpoint_ns:y};if(o){let o=r[h.node],p=o.getNode();if(p!==void 0){o.metadata!==void 0&&(b={...b,...o.metadata});let m=[];return{name:h.node,input:h.args,proc:p,subgraphs:o.subgraphs,writes:m,config:ke(bt(a,{metadata:b,tags:o.tags,store:s.store??a.store}),{runName:h.node,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Os]:v,[Cs]:e=>Bl(e=>m.push(...e),r,e),[Ts]:(n,r=!1)=>zl(t,i,{name:h.node,writes:m,triggers:g,path:e},n,r),[Es]:l??d.__pregel_checkpointer,[Rs]:{...d[Rs],[f]:t.id},[Ms]:Jl({pendingWrites:n??[],taskId:v,currentTaskInput:h.args,resumeMap:a.configurable?.[js],namespaceHash:Xc(y)}),[Ns]:t.channel_values[Us],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:g,retry_policy:o.retryPolicy,cache_key:o.cachePolicy?{key:Xc((o.cachePolicy.keyFunc??JSON.stringify)([h.args])),ns:[Ss,o.name??`__dynamic__`,h.node],ttl:o.cachePolicy.ttl}:void 0,id:v,path:e,writers:o.getWriters()}}}else return{id:v,name:h.node,interrupts:[],path:e}}else if(e[0]===`__pregel_pull`){let p=e[1].toString(),m=r[p];if(m===void 0)return;if(n?.length){let e=f===``?p:`${f}|${p}`,r=$n(JSON.stringify([e,c.toString(),p,qs,p]),t.id);if(n.some(e=>e[0]===r&&e[1]!==`__error__`))return}let h=wl(t.channel_versions);if(h===void 0)return;let g=t.versions_seen[p]??{},_=m.triggers.find(e=>i[e].isAvailable()?(t.channel_versions[e]??h)>(g[e]??h):!1);if(_!==void 0){let h=Kl(m,i,o);if(h===void 0)return;let g=f===``?p:`${f}|${p}`,v=$n(JSON.stringify([g,c.toString(),p,qs,[_]]),t.id),y=`${g}:${v}`,b={langgraph_step:c,langgraph_node:p,langgraph_triggers:[_],langgraph_path:e,langgraph_checkpoint_ns:y};if(o){let o=m.getNode();if(o!==void 0){m.metadata!==void 0&&(b={...b,...m.metadata});let g=[];return{name:p,input:h,proc:o,subgraphs:m.subgraphs,writes:g,config:ke(bt(a,{metadata:b,tags:m.tags,store:s.store??a.store}),{runName:p,callbacks:u?.getChild(`graph:step:${c}`),configurable:{[Os]:v,[Cs]:e=>Bl(e=>{g.push(...e)},r,e),[Ts]:(n,r=!1)=>zl(t,i,{name:p,writes:g,triggers:[_],path:e},n,r),[Es]:l??d.__pregel_checkpointer,[Rs]:{...d[Rs],[f]:t.id},[Ms]:Jl({pendingWrites:n??[],taskId:v,currentTaskInput:h,resumeMap:a.configurable?.[js],namespaceHash:Xc(y)}),[Ns]:t.channel_values[Us],checkpoint_id:void 0,checkpoint_ns:y}}),triggers:[_],retry_policy:m.retryPolicy,cache_key:m.cachePolicy?{key:Xc((m.cachePolicy.keyFunc??JSON.stringify)([h])),ns:[Ss,m.name??`__dynamic__`,p],ttl:m.cachePolicy.ttl}:void 0,id:v,path:e,writers:m.getWriters()}}}else return{id:v,name:p,interrupts:[],path:e}}}}function Kl(e,t,n){let r;if(typeof e.channels==`object`&&!Array.isArray(e.channels)){r={};for(let[n,i]of Object.entries(e.channels))if(e.triggers.includes(i))try{r[n]=vl(t,i,!1)}catch(e){if(e.name===N.unminifiable_name)return;throw e}else if(i in t)try{r[n]=vl(t,i,!1)}catch(e){if(e.name===N.unminifiable_name)continue;throw e}}else if(Array.isArray(e.channels)){let n=!1;for(let i of e.channels)try{r=vl(t,i,!1),n=!0;break}catch(e){if(e.name===N.unminifiable_name)continue;throw e}if(!n)return}else throw Error(`Invalid channels type, expected list or dict, got ${e.channels}`);return n&&e.mapper!==void 0&&(r=e.mapper(r)),r}function ql(e,t){if(typeof e.args!=`object`||e.args===null)return e;let n={};for(let[r,i]of Object.entries(e.args)){let e=t[r];(!e||e.lc_graph_name!==`UntrackedValue`)&&(n[r]=i)}return new H(e.node,n)}function Jl({pendingWrites:e,taskId:t,currentTaskInput:n,resumeMap:r,namespaceHash:i}){let a=e.find(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`)?.[2],o={callCounter:0,interruptCounter:-1,resume:(()=>{let n=e.filter(([e,n])=>e===t&&n===`__resume__`).flatMap(([e,t,n])=>n);if(r!=null&&i in r){let e=r[i];n.push(e)}return n})(),nullResume:a,subgraphCounter:0,currentTaskInput:n,consumeNullResume:()=>{if(o.nullResume)return delete o.nullResume,e.splice(e.findIndex(([e,t])=>e===`00000000-0000-0000-0000-000000000000`&&t===`__resume__`),1),a}};return o}var Yl={blue:{start:`\x1B[34m`,end:`\x1B[0m`},green:{start:`\x1B[32m`,end:`\x1B[0m`},yellow:{start:`\x1B[33;1m`,end:`\x1B[0m`}},Xl=(e,t)=>`${e.start}${t}${e.end}`;function*Zl(e){for(let{id:t,name:n,input:r,config:i,triggers:a,writes:o}of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:t,name:n,input:r,triggers:a,interrupts:o.filter(([e,n])=>e===t&&n===`__interrupt__`).map(([,e])=>e)})}function Ql(e){return typeof e!=`object`||!e?!1:`$writes`in e&&Array.isArray(e.$writes)}function $l(e){let t={};for(let[n,r]of e){let e=String(n);if(e in t){let n=Ql(t[e])?t[e].$writes:[t[e]];n.push(r),t[e]={$writes:n}}else t[e]=r}return t}function*eu(e,t){for(let[{id:n,name:r,config:i},a]of e)i?.tags?.includes(`langsmith:hidden`)||(yield{id:n,name:r,result:$l(a.filter(([e])=>Array.isArray(t)?t.includes(e):e===t)),interrupts:a.filter(e=>e[0]===B).map(e=>e[1])})}function*tu(e,t,n,r,i,a,o,s){function c(e){let t={};return e.callbacks!=null&&(t.callbacks=e.callbacks),e.configurable!=null&&(t.configurable=e.configurable),e.maxConcurrency!=null&&(t.max_concurrency=e.maxConcurrency),e.metadata!=null&&(t.metadata=e.metadata),e.recursionLimit!=null&&(t.recursion_limit=e.recursionLimit),e.runId!=null&&(t.run_id=e.runId),e.runName!=null&&(t.run_name=e.runName),e.tags!=null&&(t.tags=e.tags),t}let l=e.configurable?.checkpoint_ns,u={};for(let t of i){if(!(t.subgraphs?.length?t.subgraphs:[t.proc]).find(_l))continue;let n=`${t.name}:${t.id}`;l&&(n=`${l}|${n}`),u[t.id]={configurable:{thread_id:e.configurable?.thread_id,checkpoint_ns:n}}}yield{config:c(e),values:yl(t,n),metadata:r,next:i.map(e=>e.name),tasks:nu(i,a,u,s),parentConfig:o?c(o):void 0}}function nu(e,t,n,r){return e.map(e=>{let i=t.find(([t,n])=>t===e.id&&n===`__error__`)?.[2],a=t.filter(([t,n])=>t===e.id&&n===`__interrupt__`).map(([,,e])=>e),o=(()=>{if(i||a.length||!t.length)return;let n=t.findIndex(([t,n])=>t===e.id&&n===`__return__`);if(n>=0)return t[n][2];if(typeof r==`string`)return t.find(([t,n])=>t===e.id&&n===r)?.[2];if(Array.isArray(r)){let n=t.filter(([t,n])=>t===e.id&&r.includes(n)).map(([,e,t])=>[e,t]);return n.length?$l(n):void 0}})();if(i)return{id:e.id,name:e.name,path:e.path,error:i,interrupts:a,result:o};let s=n?.[e.id];return{id:e.id,name:e.name,path:e.path,interrupts:a,...s===void 0?{}:{state:s},result:o}})}function ru(e,t,n){console.log([`${Xl(Yl.blue,`[${e}:checkpoint]`)}`,`\x1b[1m State at the end of step ${e}:\x1b[0m\n`,JSON.stringify(yl(t,n),null,2)].join(``))}function iu(e,t){let n=t.length;console.log([`${Xl(Yl.blue,`[${e}:tasks]`)}`,`\x1b[1m Starting step ${e} with ${n} task${n===1?``:`s`}:\x1b[0m\n`,t.map(e=>`- ${Xl(Yl.green,String(e.name))} -> ${JSON.stringify(e.input,null,2)}`).join(`
|
|
25
25
|
`)].join(``))}function au(e,t,n){let r={};for(let[e,i]of t)n.includes(e)&&(r[e]||(r[e]=[]),r[e].push(i));console.log([`${Xl(Yl.blue,`[${e}:writes]`)}`,`\x1b[1m Finished step ${e} with writes to ${Object.keys(r).length} channel${Object.keys(r).length===1?``:`s`}:\x1b[0m\n`,Object.entries(r).map(([e,t])=>`- ${Xl(Yl.yellow,e)} -> ${t.map(e=>JSON.stringify(e)).join(`, `)}`).join(`
|
|
26
26
|
`)].join(``))}var ou=class extends Pe{_abortController;_innerReader;constructor(e,t){let n=e.getReader(),r=t??new AbortController;super({start(e){return t();function t(){return n.read().then(({done:n,value:r})=>{if(n){e.close();return}return e.enqueue(r),t()})}}}),this._abortController=r,this._innerReader=n}async cancel(e){this._abortController.abort(e),this._innerReader.releaseLock()}get signal(){return this._abortController.signal}},su=class extends Pe{modes;controller;passthroughFn;_closed=!1;get closed(){return this._closed}constructor(e){let t,n=new Promise(e=>{t=e});super({start:e=>{t(e)}}),n.then(e=>{this.controller=e}),this.passthroughFn=e.passthroughFn,this.modes=e.modes}push(e){this.passthroughFn?.(e),this.controller.enqueue(e)}close(){try{this.controller.close()}catch{}finally{this._closed=!0}}error(e){this.controller.error(e)}};function cu(e){return JSON.stringify(e,function(e,t){let n=this[e];if(typeof n==`object`&&n&&`toDict`in n&&typeof n.toDict==`function`){let{type:e,data:t}=n.toDict();return{...t,type:e}}return t})}function lu(e){return e instanceof Error?{error:e.name,message:e.message}:{error:`Error`,message:JSON.stringify(e)}}function uu(e){return typeof e!=`object`||!e?!1:`configurable`in e&&typeof e.configurable==`object`&&e.configurable!=null}function du(e){return!uu(e)||!e.configurable.thread_id?null:{thread_id:e.configurable.thread_id,checkpoint_ns:e.configurable.checkpoint_ns||``,checkpoint_id:e.configurable.checkpoint_id||null,checkpoint_map:e.configurable.checkpoint_map||null}}function fu(e){if(uu(e)){let t=Object.fromEntries(Object.entries(e.configurable).filter(([e])=>!e.startsWith(`__`))),n={...e,configurable:t};return delete n.callbacks,n}return e}function pu(e){let t={...e,checkpoint:du(e.config),parent_checkpoint:du(e.parentConfig),config:fu(e.config),parent_config:fu(e.parentConfig),tasks:e.tasks.map(e=>{if(uu(e.state)){let t=du(e.state);if(t!=null){let n={...e,checkpoint:t};return delete n.state,n}}return e})};return delete t.parentConfig,t}function mu(e){let t=new TextEncoder;return new ReadableStream({async start(n){let r=e=>{n.enqueue(t.encode(`event: ${e.event}\ndata: ${cu(e.data)}\n\n`))};try{for await(let t of e){let[e,n,i]=t,a=i;if(n===`debug`){let e=i;e.type===`checkpoint`&&(a={...e,payload:pu(e.payload)})}n===`checkpoints`&&(a=pu(i)),r({event:e?.length?`${n}|${e.join(`|`)}`:n,data:a})}}catch(e){r({event:`error`,data:lu(e)})}n.close()}})}var hu=Symbol.for(`INPUT_DONE`),gu=Symbol.for(`INPUT_RESUMING`),_u=25;function vu(...e){return new su({passthroughFn:t=>{for(let n of e)n.modes.has(t[1])&&n.push(t)},modes:new Set(e.flatMap(e=>Array.from(e.modes)))})}var yu=class extends os{cache;queue=Promise.resolve();constructor(e){super(),this.cache=e}async get(e){return this.enqueueOperation(`get`,e)}async set(e){return this.enqueueOperation(`set`,e)}async clear(e){return this.enqueueOperation(`clear`,e)}async stop(){await this.queue}enqueueOperation(e,...t){let n=this.queue.then(()=>this.cache[e](...t));return this.queue=n.then(()=>void 0,()=>void 0),n}},bu=class e{input;output;config;checkpointer;checkpointerGetNextVersion;channels;checkpoint;checkpointIdSaved;checkpointConfig;checkpointMetadata;checkpointNamespace;checkpointPendingWrites=[];checkpointPreviousVersions;step;stop;durability;outputKeys;streamKeys;nodes;skipDoneTasks;prevCheckpointConfig;updatedChannels;status=`pending`;tasks={};stream;checkpointerPromises=[];isNested;_checkpointerChainedPromise=Promise.resolve();store;cache;manager;interruptAfter;interruptBefore;toInterrupt=[];debug=!1;triggerToNodes;get isResuming(){let e=!1;if(`__start__`in this.checkpoint.channel_versions)e=!0;else for(let t in this.checkpoint.channel_versions)if(Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions,t)){e=!0;break}let t=this.config.configurable?.__pregel_resuming!==void 0&&this.config.configurable?.__pregel_resuming,n=this.input===null||this.input===void 0,r=G(this.input)&&this.input.resume!=null,i=this.input===gu,a=!this.isNested&&this.config.metadata?.run_id!==void 0&&this.checkpointMetadata?.run_id!==void 0&&this.config.metadata.run_id===this.checkpointMetadata?.run_id;return e&&(t||n||r||i||a)}constructor(e){this.input=e.input,this.checkpointer=e.checkpointer,this.checkpointer===void 0?this.checkpointerGetNextVersion=Fl:this.checkpointerGetNextVersion=this.checkpointer.getNextVersion.bind(this.checkpointer),this.checkpoint=e.checkpoint,this.checkpointMetadata=e.checkpointMetadata,this.checkpointPreviousVersions=e.checkpointPreviousVersions,this.channels=e.channels,this.checkpointPendingWrites=e.checkpointPendingWrites,this.step=e.step,this.stop=e.stop,this.config=e.config,this.checkpointConfig=e.checkpointConfig,this.isNested=e.isNested,this.manager=e.manager,this.outputKeys=e.outputKeys,this.streamKeys=e.streamKeys,this.nodes=e.nodes,this.skipDoneTasks=e.skipDoneTasks,this.store=e.store,this.cache=e.cache?new yu(e.cache):void 0,this.stream=e.stream,this.checkpointNamespace=e.checkpointNamespace,this.prevCheckpointConfig=e.prevCheckpointConfig,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.durability=e.durability,this.debug=e.debug,this.triggerToNodes=e.triggerToNodes}static async initialize(t){let{config:n,stream:r}=t;r!==void 0&&n.configurable?.__pregel_stream!==void 0&&(r=vu(r,n.configurable[ks]));let i=n.configurable?!(`checkpoint_id`in n.configurable):!0,a=n.configurable?.[Ms];n.configurable&&a&&(a.subgraphCounter>0&&(n=Dl(n,{[Is]:[n.configurable[Is],a.subgraphCounter.toString()].join(`|`)})),a.subgraphCounter+=1);let o=Ts in(n.configurable??{});!o&&n.configurable?.checkpoint_ns!==void 0&&n.configurable?.checkpoint_ns!==``&&(n=Dl(n,{checkpoint_ns:``,checkpoint_id:void 0}));let s=n;n.configurable?.checkpoint_map!==void 0&&n.configurable?.checkpoint_map?.[n.configurable?.checkpoint_ns]&&(s=Dl(n,{checkpoint_id:n.configurable[Rs][n.configurable?.checkpoint_ns]}));let c=n.configurable?.checkpoint_ns?.split(`|`)??[],l=await t.checkpointer?.getTuple(s)??{config:n,checkpoint:Xo(),metadata:{source:`input`,step:-2,parents:{}},pendingWrites:[]};s={...n,...l.config,configurable:{checkpoint_ns:``,...n.configurable,...l.config.configurable}};let u=l.parentConfig,d=Zo(l.checkpoint),f={...l.metadata},p=l.pendingWrites??[],m=ds(t.channelSpecs,d),h=(f.step??0)+1,g=h+(n.recursionLimit??_u)+1,_={...d.channel_versions},v=t.store?new as(t.store):void 0;return v&&await v.start(),new e({input:t.input,config:n,checkpointer:t.checkpointer,checkpoint:d,checkpointMetadata:f,checkpointConfig:s,prevCheckpointConfig:u,checkpointNamespace:c,channels:m,isNested:o,manager:t.manager,skipDoneTasks:i,step:h,stop:g,checkpointPreviousVersions:_,checkpointPendingWrites:p,outputKeys:t.outputKeys??[],streamKeys:t.streamKeys??[],nodes:t.nodes,stream:r,store:v,cache:t.cache,interruptAfter:t.interruptAfter,interruptBefore:t.interruptBefore,durability:t.durability,debug:t.debug,triggerToNodes:t.triggerToNodes})}_checkpointerPutAfterPrevious(e){this._checkpointerChainedPromise=this._checkpointerChainedPromise.then(()=>this.checkpointer?.put(e.config,e.checkpoint,e.metadata,e.newVersions)),this.checkpointerPromises.push(this._checkpointerChainedPromise)}putWrites(e,t){let n=t;if(n.length===0)return;n.every(([e])=>e in es)&&(n=Array.from(new Map(n.map(e=>[e[0],e])).values()));let r=!1;for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.channels[e].lc_graph_name===`UntrackedValue`){r=!0;break}let i=n;r&&(i=n.filter(([e])=>{let t=this.channels[e];return!t||t.lc_graph_name!==`UntrackedValue`}).map(([e,t])=>e===`__pregel_tasks`&&U(t)?[e,ql(t,this.channels)]:[e,t])),this.checkpointPendingWrites=this.checkpointPendingWrites.filter(t=>t[0]!==e);for(let[t,n]of i)this.checkpointPendingWrites.push([e,t,n]);let a=Dl(this.checkpointConfig,{[Is]:this.config.configurable?.checkpoint_ns??``,[Fs]:this.checkpoint.id});if(this.durability!==`exit`&&this.checkpointer!=null&&this.checkpointerPromises.push(this.checkpointer.putWrites(a,i,e)),this.tasks&&this._outputWrites(e,n),!t.length||!this.cache||!this.tasks)return;let o=this.tasks[e];o==null||o.cache_key==null||t[0][0]===`__error__`||t[0][0]===`__interrupt__`||this.cache.set([{key:[o.cache_key.ns,o.cache_key.key],value:o.writes,ttl:o.cache_key.ttl}])}_outputWrites(e,t,n=!1){let r=this.tasks[e];if(r!==void 0){if(r.config!==void 0&&(r.config.tags??[]).includes(`langsmith:hidden`))return;if(t.length>0)if(t[0][0]===`__interrupt__`){if(r.path?.[0]===`__pregel_push`&&r.path?.[r.path.length-1]===!0)return;let e=t.filter(e=>e[0]===B).flatMap(e=>e[1]);this._emit([[`updates`,{[B]:e}],[`values`,{[B]:e}]])}else t[0][0]!==`__error__`&&this._emit(nl(el(Cl(this.outputKeys,[[r,t]],n),`updates`)));n||this._emit(nl(el(eu([[r,t]],this.streamKeys),`tasks`)))}}async _matchCachedWrites(){if(!this.cache)return[];let e=[],t=([e,t])=>`ns:${e.join(`,`)}|key:${t}`,n=[],r={};for(let e of Object.values(this.tasks))e.cache_key!=null&&!e.writes.length&&(n.push([e.cache_key.ns,e.cache_key.key]),r[t([e.cache_key.ns,e.cache_key.key])]=e);if(n.length===0)return[];let i=await this.cache.get(n);for(let{key:n,value:a}of i){let i=r[t(n)];i!=null&&(i.writes.push(...a),e.push({task:i,result:a}))}return e}async tick(e){this.store&&!this.store.isRunning&&await this.store?.start();let{inputKeys:t=[]}=e;if(this.status!==`pending`)throw Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`);if(![hu,gu].includes(this.input))await this._first(t);else if(this.toInterrupt.length>0)throw this.status=`interrupt_before`,new Un;else if(Object.values(this.tasks).every(e=>e.writes.length>0)){let e=Object.values(this.tasks).flatMap(e=>e.writes);this.updatedChannels=Hl(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes);let t=await tl(el(Sl(this.outputKeys,e,this.channels),`values`));if(this._emit(t),this.checkpointPendingWrites=[],await this._putCheckpoint({source:`loop`}),Rl(this.checkpoint,this.interruptAfter,Object.values(this.tasks)))throw this.status=`interrupt_after`,new Un;this.config.configurable?.__pregel_resuming!==void 0&&delete this.config.configurable?.[Ds]}else return!1;if(this.step>this.stop)return this.status=`out_of_steps`,!1;if(this.tasks=Wl(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step,checkpointer:this.checkpointer,isResuming:this.isResuming,manager:this.manager,store:this.store,stream:this.stream,triggerToNodes:this.triggerToNodes,updatedChannels:this.updatedChannels}),this.checkpointer&&this._emit(await tl(el(tu(this.checkpointConfig,this.channels,this.streamKeys,this.checkpointMetadata,Object.values(this.tasks),this.checkpointPendingWrites,this.prevCheckpointConfig,this.outputKeys),`checkpoints`))),Object.values(this.tasks).length===0)return this.status=`done`,!1;if(this.skipDoneTasks&&this.checkpointPendingWrites.length>0){for(let[e,t,n]of this.checkpointPendingWrites){if(t===`__error__`||t===`__interrupt__`||t===`__resume__`)continue;let r=Object.values(this.tasks).find(t=>t.id===e);r&&r.writes.push([t,n])}for(let e of Object.values(this.tasks))e.writes.length>0&&this._outputWrites(e.id,e.writes,!0)}if(Object.values(this.tasks).every(e=>e.writes.length>0))return this.tick({inputKeys:t});if(Rl(this.checkpoint,this.interruptBefore,Object.values(this.tasks)))throw this.status=`interrupt_before`,new Un;let n=await tl(el(Zl(Object.values(this.tasks)),`tasks`));return this._emit(n),!0}async finishAndHandleError(e){this.durability===`exit`&&(!this.isNested||e!==void 0||this.checkpointNamespace.every(e=>!e.includes(`:`)))&&(this._putCheckpoint(this.checkpointMetadata),this._flushPendingWrites());let t=this._suppressInterrupt(e);return(t||e===void 0)&&(this.output=yl(this.channels,this.outputKeys)),t&&(this.tasks!==void 0&&this.checkpointPendingWrites.length>0&&Object.values(this.tasks).some(e=>e.writes.length>0)&&(this.updatedChannels=Hl(this.checkpoint,this.channels,Object.values(this.tasks),this.checkpointerGetNextVersion,this.triggerToNodes),this._emit(nl(el(Sl(this.outputKeys,Object.values(this.tasks).flatMap(e=>e.writes),this.channels),`values`)))),Jn(e)&&!e.interrupts.length&&this._emit([[`updates`,{[B]:[]}],[`values`,{[B]:[]}]])),t}async acceptPush(e,t,n){if(this.interruptAfter?.length>0&&Rl(this.checkpoint,this.interruptAfter,[e])){this.toInterrupt.push(e);return}let r=Gl([Ks,e.path??[],t,e.id,n],this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,e.config??{},!0,{step:this.step,checkpointer:this.checkpointer,manager:this.manager,store:this.store,stream:this.stream});if(!r)return;if(this.interruptBefore?.length>0&&Rl(this.checkpoint,this.interruptBefore,[r])){this.toInterrupt.push(r);return}this._emit(nl(el(Zl([r]),`tasks`))),this.debug&&iu(this.step,[r]),this.tasks[r.id]=r,this.skipDoneTasks&&this._matchWrites({[r.id]:r});let i=await this._matchCachedWrites();for(let{task:e}of i)this._outputWrites(e.id,e.writes,!0);return r}_suppressInterrupt(e){return Jn(e)&&!this.isNested}async _first(e){let{configurable:t}=this.config,n=t?.[Ms];if(n&&n.nullResume!==void 0&&this.putWrites(Js,[[Bs,n.nullResume]]),G(this.input)){let e=this.input.resume!=null;if(this.input.resume!=null&&typeof this.input.resume==`object`&&Object.keys(this.input.resume).every(Zc)&&(this.config.configurable??={},this.config.configurable[js]=this.input.resume),e&&this.checkpointer==null)throw Error(`Cannot use Command(resume=...) without checkpointer`);let t={};for(let[e,n,r]of bl(this.input,this.checkpointPendingWrites))t[e]??=[],t[e].push([n,r]);if(Object.keys(t).length===0)throw new Yn(`Received empty Command input`);for(let[e,n]of Object.entries(t))this.putWrites(e,n)}let r=(this.checkpointPendingWrites??[]).filter(e=>e[0]===Js).map(e=>e.slice(1));r.length>0&&Hl(this.checkpoint,this.channels,[{name:bs,writes:r,triggers:[]}],this.checkpointerGetNextVersion,this.triggerToNodes);let i=G(this.input)&&r.length>0;if(this.isResuming||i){for(let e in this.channels)if(Object.prototype.hasOwnProperty.call(this.channels,e)&&this.checkpoint.channel_versions[e]!==void 0){let t=this.checkpoint.channel_versions[e];this.checkpoint.versions_seen[B]={...this.checkpoint.versions_seen[B],[e]:t}}let e=await tl(el(Sl(this.outputKeys,!0,this.channels),`values`));this._emit(e)}if(this.isResuming)this.input=gu;else if(i)await this._putCheckpoint({source:`input`}),this.input=hu;else{let t=await tl(xl(e,this.input));if(t.length>0){let e=Wl(this.checkpoint,this.checkpointPendingWrites,this.nodes,this.channels,this.config,!0,{step:this.step});this.updatedChannels=Hl(this.checkpoint,this.channels,Object.values(e).concat([{name:bs,writes:t,triggers:[]}]),this.checkpointerGetNextVersion,this.triggerToNodes),await this._putCheckpoint({source:`input`}),this.input=hu}else if(`__pregel_resuming`in(this.config.configurable??{}))this.input=hu;else throw new Yn(`Received no input writes for ${JSON.stringify(e,null,2)}`)}this.isNested||(this.config=Dl(this.config,{[Ds]:this.isResuming}))}_emit(e){for(let[t,n]of e)if(this.stream.modes.has(t)&&this.stream.push([this.checkpointNamespace,t,n]),(t===`checkpoints`||t===`tasks`)&&this.stream.modes.has(`debug`)){let e=t===`checkpoints`?this.step-1:this.step,r=new Date().toISOString(),i=t===`checkpoints`?`checkpoint`:typeof n==`object`&&n&&`result`in n?`task_result`:`task`;this.stream.push([this.checkpointNamespace,`debug`,{step:e,type:i,timestamp:r,payload:n}])}}_putCheckpoint(e){let t=this.checkpointMetadata===e,n=this.checkpointer!=null&&(this.durability!==`exit`||t),r=e=>{this.prevCheckpointConfig=this.checkpointConfig?.configurable?.checkpoint_id?this.checkpointConfig:void 0,this.checkpointConfig=Dl(this.checkpointConfig,{[Is]:this.config.configurable?.checkpoint_ns??``});let t={...this.checkpoint.channel_versions},n=Tl(this.checkpointPreviousVersions,t);this.checkpointPreviousVersions=t,this._checkpointerPutAfterPrevious({config:{...this.checkpointConfig},checkpoint:Zo(e),metadata:{...this.checkpointMetadata},newVersions:n}),this.checkpointConfig={...this.checkpointConfig,configurable:{...this.checkpointConfig.configurable,checkpoint_id:this.checkpoint.id}}};t||(this.checkpointMetadata={...e,step:this.step,parents:this.config.configurable?.checkpoint_map??{}}),this.checkpoint=fs(this.checkpoint,n?this.channels:void 0,this.step,t?{id:this.checkpoint.id}:void 0),n&&r(this.checkpoint),t||(this.step+=1)}_flushPendingWrites(){if(this.checkpointer==null||this.checkpointPendingWrites.length===0)return;let e=Dl(this.checkpointConfig,{[Is]:this.config.configurable?.checkpoint_ns??``,[Fs]:this.checkpoint.id}),t={};for(let[e,n,r]of this.checkpointPendingWrites)t[e]??=[],t[e].push([n,r]);for(let[n,r]of Object.entries(t))this.checkpointerPromises.push(this.checkpointer.putWrites(e,r,n))}_matchWrites(e){for(let[t,n,r]of this.checkpointPendingWrites){if(n===`__error__`||n===`__interrupt__`||n===`__resume__`)continue;let i=Object.values(e).find(e=>e.id===t);i&&i.writes.push([n,r])}for(let t of Object.values(e))t.writes.length>0&&this._outputWrites(t.id,t.writes,!0)}};function xu(e){return s(e?.message)}var Su=class extends ie{name=`StreamMessagesHandler`;streamFn;metadatas={};seen={};emittedChatModelRunIds={};stableMessageIdMap={};lc_prefer_streaming=!0;constructor(e){super(),this.streamFn=e}_emit(e,t,n,r=!1){if(r&&t.id!==void 0&&this.seen[t.id]!==void 0)return;let i=t.id;n!=null&&(yt(t)?i??=`run-${n}-tool-${t.tool_call_id}`:((i==null||i===`run-${n}`)&&(i=this.stableMessageIdMap[n]??i??`run-${n}`),this.stableMessageIdMap[n]??=i)),i!==t.id&&(t.id=i,t.lc_kwargs.id=i),t.id!=null&&(this.seen[t.id]=t),this.streamFn([e[0],`messages`,[t,e[1]]])}handleChatModelStart(e,t,n,r,i,a,o,s){o&&(!a||!a.includes(`langsmith:nostream`)&&!a.includes(`nostream`))&&(this.metadatas[n]=[o.langgraph_checkpoint_ns.split(`|`),{tags:a,name:s,...o}])}handleLLMNewToken(e,t,n,r,i,a){let o=a?.chunk;this.emittedChatModelRunIds[n]=!0,this.metadatas[n]!==void 0&&(xu(o)?this._emit(this.metadatas[n],o.message,n):this._emit(this.metadatas[n],new we({content:e}),n))}handleLLMEnd(e,t){if(this.metadatas[t]!==void 0){if(!this.emittedChatModelRunIds[t]){let n=e.generations?.[0]?.[0];s(n?.message)&&this._emit(this.metadatas[t],n?.message,t,!0),delete this.emittedChatModelRunIds[t]}delete this.metadatas[t],delete this.stableMessageIdMap[t]}}handleLLMError(e,t){delete this.metadatas[t]}handleChainStart(e,t,n,r,i,a,o,c){if(a!==void 0&&c===a.langgraph_node&&(i===void 0||!i.includes(`langsmith:hidden`))&&(this.metadatas[n]=[a.langgraph_checkpoint_ns.split(`|`),{tags:i,name:c,...a}],typeof t==`object`)){for(let e of Object.values(t))if((s(e)||pt(e))&&e.id!==void 0)this.seen[e.id]=e;else if(Array.isArray(e))for(let t of e)(s(t)||pt(t))&&t.id!==void 0&&(this.seen[t.id]=t)}}handleChainEnd(e,t){let n=this.metadatas[t];if(delete this.metadatas[t],n!==void 0){if(s(e))this._emit(n,e,t,!0);else if(Array.isArray(e))for(let r of e)s(r)&&this._emit(n,r,t,!0);else if(typeof e==`object`&&e){for(let r of Object.values(e))if(s(r))this._emit(n,r,t,!0);else if(Array.isArray(r))for(let e of r)s(e)&&this._emit(n,e,t,!0)}}}handleChainError(e,t){delete this.metadatas[t]}},Cu=500,wu=2,Tu=128e3,Eu=3,Du=[400,401,402,403,404,405,406,407,409],Ou=e=>{if(e.message.startsWith(`Cancel`)||e.message.startsWith(`AbortError`)||e.name===`AbortError`||e.name===`GraphValueError`||e?.code===`ECONNABORTED`)return!1;let t=e?.response?.status??e?.status;return!(t&&Du.includes(+t)||e?.error?.code===`insufficient_quota`)};async function ku(e,t,n,r){let i=e.retry_policy??t,a=i===void 0?0:i.initialInterval??Cu,o=0,s,c,{config:l}=e;for(n&&(l=Dl(l,n)),l={...l,signal:r};!r?.aborted;){e.writes.splice(0,e.writes.length),s=void 0;try{c=await e.proc.invoke(e.input,l);break}catch(t){if(s=t,s.pregelTaskId=e.id,Kn(s)){let t=l?.configurable?.checkpoint_ns,n=s.command;if(n.graph===t){for(let t of e.writers)await t.invoke(n,l);s=void 0;break}else if(n.graph===W.PARENT){let e=sc(t);s.command=new W({...s.command,graph:e})}}if(qn(s)||i===void 0||(o+=1,o>=(i.maxAttempts??Eu))||!(i.retryOn??Ou)(s))break;a=Math.min(i.maxInterval??Tu,a*(i.backoffFactor??wu));let n=i.jitter?Math.floor(a+Math.random()*1e3):a;await new Promise(e=>setTimeout(e,n));let r=s.name??s.constructor.unminifiable_name??s.constructor.name;(i?.logWarning??!0)&&console.log(`Retrying task "${String(e.name)}" after ${a.toFixed(2)}ms (attempt ${o}) after ${r}: ${s}`),l=Dl(l,{[Ds]:!0})}}return{task:e,result:c,error:s,signalAborted:r?.aborted}}var Au=Symbol.for(`promiseAdded`);function ju(){let e={next:()=>void 0,wait:Promise.resolve(Au)};function t(n){e.next=()=>{e.wait=new Promise(t),n(Au)}}return e.wait=new Promise(t),e}var Mu=class{nodeFinished;loop;constructor({loop:e,nodeFinished:t}){this.loop=e,this.nodeFinished=t}async tick(e={}){let{timeout:t,retryPolicy:n,onStepWrite:r,maxConcurrency:i}=e,a=new Set,o,s=new AbortController,c=s.signal,l=t?AbortSignal.timeout(t):void 0,u=Object.values(this.loop.tasks).filter(e=>e.writes.length===0),{signals:d,disposeCombinedSignal:f}=this._initializeAbortSignals({exceptionSignal:c,stepTimeoutSignal:l,signal:e.signal}),p=this._executeTasksWithRetry(u,{signals:d,retryPolicy:n,maxConcurrency:i});for await(let{task:e,error:t,signalAborted:n}of p)this._commit(e,t),Jn(t)||qn(t)&&!Jn(o)?o=t:t&&(a.size===0||!n)&&(s.abort(),a.add(t));if(f?.(),r?.(this.loop.step,Object.values(this.loop.tasks).map(e=>e.writes).flat()),a.size===1)throw Array.from(a)[0];if(a.size>1)throw AggregateError(Array.from(a),`Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`);if(Jn(o)||qn(o)&&this.loop.isNested)throw o}_initializeAbortSignals({exceptionSignal:e,stepTimeoutSignal:t,signal:n}){let r=this.loop.config.configurable?.__pregel_abort_signals??{},i=r.externalAbortSignal??n,a=t??r.timeoutAbortSignal,{signal:o,dispose:s}=kl(i,a,e),c={externalAbortSignal:i,timeoutAbortSignal:a,composedAbortSignal:o};return this.loop.config=Dl(this.loop.config,{[zs]:c}),{signals:c,disposeCombinedSignal:s}}async*_executeTasksWithRetry(e,t){let{retryPolicy:n,maxConcurrency:r,signals:i}=t??{},a=ju(),o={},s={executingTasksMap:o,barrier:a,retryPolicy:n,scheduleTask:async(e,t,n)=>this.loop.acceptPush(e,t,n)};if(i?.composedAbortSignal?.aborted)throw Error(`Abort`);let c=0,l,u=kl(i?.externalAbortSignal,i?.timeoutAbortSignal),d=u.signal?new Promise((e,t)=>{l=()=>t(Error(`Abort`)),u.signal?.addEventListener(`abort`,l,{once:!0})}):void 0;for(;(c===0||Object.keys(o).length>0)&&e.length;){for(;Object.values(o).length<(r??e.length)&&c<e.length;c+=1){let t=e[c];o[t.id]=ku(t,n,{[ws]:Nu?.bind(s,this,t)},i?.composedAbortSignal).catch(e=>({task:t,error:e,signalAborted:i?.composedAbortSignal?.aborted}))}let t=await Promise.race([...Object.values(o),...d?[d]:[],a.wait]);t!==Au&&(yield t,l!=null&&(u.signal?.removeEventListener(`abort`,l),u.dispose?.()),delete o[t.task.id])}}_commit(e,t){if(t!==void 0)if(Jn(t)){if(t.interrupts.length){let n=t.interrupts.map(e=>[B,e]),r=e.writes.filter(e=>e[0]===Bs);r.length&&n.push(...r),this.loop.putWrites(e.id,n)}}else qn(t)&&e.writes.length?this.loop.putWrites(e.id,e.writes):this.loop.putWrites(e.id,[[xs,{message:t.message,name:t.name}]]);else this.nodeFinished&&(e.config?.tags==null||!e.config.tags.includes(`langsmith:hidden`))&&this.nodeFinished(String(e.name)),e.writes.length===0&&e.writes.push([Vs,null]),this.loop.putWrites(e.id,e.writes)}};async function Nu(e,t,n,r,i,a={}){let o=t.config?.configurable?.[Ms];if(!o)throw Error(`BUG: No scratchpad found on task ${t.name}__${t.id}`);let s=o.callCounter;o.callCounter+=1;let c=new jl({func:n,name:r,input:i,cache:a.cache,retry:a.retry,callbacks:a.callbacks}),l=await this.scheduleTask(t,s,c);if(!l)return;let u=this.executingTasksMap[l.id];if(u!==void 0)return u;if(l.writes.length>0){let e=l.writes.filter(([e])=>e===Hs),t=l.writes.filter(([e])=>e===xs);if(e.length>0){if(e.length===1)return Promise.resolve(e[0][1]);throw Error(`BUG: multiple returns found for task ${l.name}__${l.id}`)}if(t.length>0){if(t.length===1){let e=t[0][1],n=e instanceof Error?e:Error(String(e));return Promise.reject(n)}throw Error(`BUG: multiple errors found for task ${l.name}__${l.id}`)}return}else{let t=ku(l,a.retry,{[ws]:Nu.bind(this,e,l)});return this.executingTasksMap[l.id]=t,this.barrier.next(),t.then(({result:e,error:t})=>t?Promise.reject(t):e)}}var Pu=class extends Error{constructor(e){super(e),this.name=`GraphValidationError`}};function Fu({nodes:e,channels:t,inputChannels:n,outputChannels:r,streamChannels:i,interruptAfterNodes:a,interruptBeforeNodes:o}){if(!t)throw new Pu(`Channels not provided`);let s=new Set,c=new Set;for(let[t,n]of Object.entries(e)){if(t===`__interrupt__`)throw new Pu(`"Node name ${B} is reserved"`);if(n.constructor===ml)n.triggers.forEach(e=>s.add(e));else throw new Pu(`Invalid node type ${typeof n}, expected PregelNode`)}for(let e of s)if(!(e in t))throw new Pu(`Subscribed channel '${String(e)}' not in channels`);if(!Array.isArray(n)){if(!s.has(n))throw new Pu(`Input channel ${String(n)} is not subscribed to by any node`)}else if(n.every(e=>!s.has(e)))throw new Pu(`None of the input channels ${n} are subscribed to by any node`);Array.isArray(r)?r.forEach(e=>c.add(e)):c.add(r),i&&!Array.isArray(i)?c.add(i):Array.isArray(i)&&i.forEach(e=>c.add(e));for(let e of c)if(!(e in t))throw new Pu(`Output channel '${String(e)}' not in channels`);if(a&&a!==`*`){for(let t of a)if(!(t in e))throw new Pu(`Node ${String(t)} not in nodes`)}if(o&&o!==`*`){for(let t of o)if(!(t in e))throw new Pu(`Node ${String(t)} not in nodes`)}}function Iu(e,t){if(Array.isArray(e)){for(let n of e)if(!(n in t))throw Error(`Key ${String(n)} not found in channels`)}else if(!(e in t))throw Error(`Key ${String(e)} not found in channels`)}var Lu=class e extends cs{lc_graph_name=`Topic`;unique=!1;accumulate=!1;seen;values;constructor(e){super(),this.unique=e?.unique??this.unique,this.accumulate=e?.accumulate??this.accumulate,this.seen=new Set,this.values=[]}fromCheckpoint(t){let n=new e({unique:this.unique,accumulate:this.accumulate});return t!==void 0&&(n.seen=new Set(t[0]),n.values=t[1]),n}update(e){let t=!1;this.accumulate||(t=this.values.length>0,this.values=[]);let n=e.flat();if(n.length>0)if(this.unique)for(let e of n)this.seen.has(e)||(t=!0,this.seen.add(e),this.values.push(e));else t=!0,this.values.push(...n);return t}get(){if(this.values.length===0)throw new N;return this.values}checkpoint(){return[[...this.seen],this.values]}isAvailable(){return this.values.length!==0}},Ru=class{static subscribeTo(e,t){let{key:n,tags:r}={key:void 0,tags:void 0,...t??{}};if(Array.isArray(e)&&n!==void 0)throw Error(`Can't specify a key when subscribing to multiple channels`);let i;return i=typeof e==`string`?n?{[n]:e}:[e]:Object.fromEntries(e.map(e=>[e,e])),new ml({channels:i,triggers:Array.isArray(e)?e:[e],tags:r})}static writeTo(e,t){let n=[];for(let t of e)n.push({channel:t,value:sl,skipNone:!1});for(let[e,r]of Object.entries(t??{}))E.isRunnable(r)||typeof r==`function`?n.push({channel:e,value:sl,skipNone:!0,mapper:ut(r)}):n.push({channel:e,value:r,skipNone:!1});return new Y(n)}},zu=class extends E{lc_namespace=[`langgraph`,`pregel`];invoke(e,t){throw Error(`Not implemented`)}withConfig(e){return super.withConfig(e)}stream(e,t){return super.stream(e,t)}},Bu=class extends zu{static lc_name(){return`LangGraph`}lc_namespace=[`langgraph`,`pregel`];lg_is_pregel=!0;nodes;channels;inputChannels;outputChannels;autoValidate=!0;streamMode=[`values`];streamChannels;interruptAfter;interruptBefore;stepTimeout;debug=!1;checkpointer;retryPolicy;config;store;cache;userInterrupt;triggerToNodes={};constructor(e){super(e);let{streamMode:t}=e;if(t!=null&&!Array.isArray(t)&&(t=[t]),this.nodes=e.nodes,this.channels=e.channels,`__pregel_tasks`in this.channels&&`lc_graph_name`in this.channels.__pregel_tasks&&this.channels.__pregel_tasks.lc_graph_name!==`Topic`)throw Error(`Channel '${Gs}' is reserved and cannot be used in the graph.`);this.channels[Gs]=new Lu({accumulate:!1}),this.autoValidate=e.autoValidate??this.autoValidate,this.streamMode=t??this.streamMode,this.inputChannels=e.inputChannels,this.outputChannels=e.outputChannels,this.streamChannels=e.streamChannels??this.streamChannels,this.interruptAfter=e.interruptAfter,this.interruptBefore=e.interruptBefore,this.stepTimeout=e.stepTimeout??this.stepTimeout,this.debug=e.debug??this.debug,this.checkpointer=e.checkpointer,this.retryPolicy=e.retryPolicy,this.config=e.config,this.store=e.store,this.cache=e.cache,this.name=e.name,this.triggerToNodes=e.triggerToNodes??this.triggerToNodes,this.userInterrupt=e.userInterrupt,this.autoValidate&&this.validate()}withConfig(e){let t=bt(this.config,e);return new this.constructor({...this,config:t})}validate(){Fu({nodes:this.nodes,channels:this.channels,outputChannels:this.outputChannels,inputChannels:this.inputChannels,streamChannels:this.streamChannels,interruptAfterNodes:this.interruptAfter,interruptBeforeNodes:this.interruptBefore});for(let[e,t]of Object.entries(this.nodes))for(let n of t.triggers)this.triggerToNodes[n]??=[],this.triggerToNodes[n].push(e);return this}get streamChannelsList(){return Array.isArray(this.streamChannels)?this.streamChannels:this.streamChannels?[this.streamChannels]:Object.keys(this.channels)}get streamChannelsAsIs(){return this.streamChannels?this.streamChannels:Object.keys(this.channels)}async getGraphAsync(e){return this.getGraph(e)}*getSubgraphs(e,t){for(let[n,r]of Object.entries(this.nodes)){if(e!==void 0&&!e.startsWith(n))continue;let i=r.subgraphs?.length?r.subgraphs:[r.bound];for(let r of i){let i=_l(r);if(i!==void 0){if(n===e){yield[n,i];return}if(e===void 0&&(yield[n,i]),t){let r=e;e!==void 0&&(r=e.slice(n.length+1));for(let[e,a]of i.getSubgraphs(r,t))yield[`${n}|${e}`,a]}}}}}async*getSubgraphsAsync(e,t){yield*this.getSubgraphs(e,t)}async _prepareStateSnapshot({config:e,saved:t,subgraphCheckpointer:n,applyPendingWrites:r=!1}){if(t===void 0)return{values:{},next:[],config:e,tasks:[]};let i=ds(this.channels,t.checkpoint);if(t.pendingWrites?.length){let e=t.pendingWrites.filter(([e,t])=>e===Js).map(([e,t,n])=>[String(t),n]);e.length>0&&Hl(t.checkpoint,i,[{name:bs,writes:e,triggers:[]}],void 0,this.triggerToNodes)}let a=Object.values(Wl(t.checkpoint,t.pendingWrites,this.nodes,i,t.config,!0,{step:(t.metadata?.step??-1)+1,store:this.store})),o=await tl(this.getSubgraphsAsync()),s=t.config.configurable?.checkpoint_ns??``,c={};for(let e of a){let r=o.find(([t])=>t===e.name);if(!r)continue;let i=`${String(e.name)}:${e.id}`;if(s&&(i=`${s}|${i}`),n===void 0){let n={configurable:{thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}};c[e.id]=n}else{let a={configurable:{[Es]:n,thread_id:t.config.configurable?.thread_id,checkpoint_ns:i}},o=r[1];c[e.id]=await o.getState(a,{subgraphs:!0})}}if(r&&t.pendingWrites?.length){let e=Object.fromEntries(a.map(e=>[e.id,e]));for(let[n,r,i]of t.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(r)||n in e&&e[n].writes.push([String(r),i]);let n=a.filter(e=>e.writes.length>0);n.length>0&&Hl(t.checkpoint,i,n,void 0,this.triggerToNodes)}let l=t?.metadata;l&&t?.config?.configurable?.thread_id&&(l={...l,thread_id:t.config.configurable.thread_id});let u=a.filter(e=>e.writes.length===0).map(e=>e.name);return{values:yl(i,this.streamChannelsAsIs),next:u,tasks:nu(a,t?.pendingWrites??[],c,this.streamChannelsAsIs),metadata:l,config:Ol(t.config,t.metadata),createdAt:t.checkpoint.ts,parentConfig:t.parentConfig}}async getState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Hn(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=oc(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i)return await a.getState(rl(e,{[Es]:n}),{subgraphs:t?.subgraphs});throw Error(`Subgraph with namespace "${i}" not found.`)}let i=bt(this.config,e),a=await n.getTuple(e);return await this._prepareStateSnapshot({config:i,saved:a,subgraphCheckpointer:t?.subgraphs?n:void 0,applyPendingWrites:!e.configurable?.checkpoint_id})}async*getStateHistory(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Hn(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=oc(r);for await(let[r,a]of this.getSubgraphsAsync(i,!0))if(r===i){yield*a.getStateHistory(rl(e,{[Es]:n}),t);return}throw Error(`Subgraph with namespace "${i}" not found.`)}let i=bt(this.config,e,{configurable:{checkpoint_ns:r}});for await(let e of n.list(i,t))yield this._prepareStateSnapshot({config:e.config,saved:e})}async bulkUpdateState(e,t){let n=e.configurable?.__pregel_checkpointer??this.checkpointer;if(!n)throw new Hn(`No checkpointer set`,{lc_error_code:`MISSING_CHECKPOINTER`});if(t.length===0)throw Error(`No supersteps provided`);if(t.some(e=>e.updates.length===0))throw Error(`No updates provided`);let r=e.configurable?.checkpoint_ns??``;if(r!==``&&e.configurable?.__pregel_checkpointer===void 0){let i=oc(r);for await(let[,r]of this.getSubgraphsAsync(i,!0))return await r.bulkUpdateState(rl(e,{[Es]:n}),t);throw Error(`Subgraph "${i}" not found`)}let i=async(e,t)=>{let r=this.config?bt(this.config,e):e,a=await n.getTuple(r),o=a===void 0?Xo():Zo(a.checkpoint),s={...a?.checkpoint.channel_versions},c=a?.metadata?.step??-1,l=rl(r,{checkpoint_ns:r.configurable?.checkpoint_ns??``}),u=r.metadata??{};a?.config.configurable&&(l=rl(r,a.config.configurable),u={...a.metadata,...u});let{values:d,asNode:f}=t[0];if(d==null&&f===void 0){if(t.length>1)throw new P(`Cannot create empty checkpoint with multiple updates`);return Ol(await n.put(l,fs(o,void 0,c),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},{}),a?a.metadata:void 0)}let p=ds(this.channels,o);if(d===null&&f===`__end__`){if(t.length>1)throw new P(`Cannot apply multiple updates when clearing state`);if(a){let e=Wl(o,a.pendingWrites||[],this.nodes,p,a.config,!0,{step:(a.metadata?.step??-1)+1,checkpointer:n,store:this.store}),t=(a.pendingWrites||[]).filter(e=>e[0]===Js).map(e=>e.slice(1));t.length>0&&Hl(o,p,[{name:bs,writes:t,triggers:[]}],n.getNextVersion.bind(n),this.triggerToNodes);for(let[t,n,r]of a.pendingWrites||[])[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||t in e&&e[t].writes.push([n,r]);Hl(o,p,Object.values(e),n.getNextVersion.bind(n),this.triggerToNodes)}return Ol(await n.put(l,fs(o,p,c),{...u,source:`update`,step:c+1,parents:a?.metadata?.parents??{}},Tl(s,o.channel_versions)),a?a.metadata:void 0)}if(f===`__copy__`){if(t.length>1)throw new P(`Cannot copy checkpoint with multiple updates`);if(a==null)throw new P(`Cannot copy a non-existent checkpoint`);let e=e=>!Array.isArray(e)||e.length===0?!1:e.every(e=>Array.isArray(e)&&e.length===2),r=fs(o,void 0,c),s=await n.put(a.parentConfig??rl(a.config,{checkpoint_id:void 0}),r,{source:`fork`,step:c+1,parents:a.metadata?.parents??{}},{});if(e(d)){let e=Wl(r,a.pendingWrites,this.nodes,p,s,!1,{step:c+2}),t=Object.values(e).reduce((e,{name:t,id:n})=>(e[t]??=[],e[t].push({id:n}),e),{}),n=d.reduce((e,n)=>{let[r,i]=n;e[i]??=[];let a=e[i].length,o=t[i]?.[a]?.id;return e[i].push({values:r,asNode:i,taskId:o}),e},{});return i(Ol(s,a.metadata),Object.values(n).flat())}return Ol(s,a.metadata)}if(f===`__input__`){if(t.length>1)throw new P(`Cannot apply multiple updates when updating as input`);let e=await tl(xl(this.inputChannels,d));if(e.length===0)throw new P(`Received no input writes for ${JSON.stringify(this.inputChannels,null,2)}`);Hl(o,p,[{name:bs,writes:e,triggers:[]}],n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let r=a?.metadata?.step==null?-1:a.metadata.step+1,i=await n.put(l,fs(o,p,r),{source:`input`,step:r,parents:a?.metadata?.parents??{}},Tl(s,o.channel_versions));return await n.putWrites(i,e,$n(bs,o.id)),Ol(i,a?a.metadata:void 0)}if(r.configurable?.checkpoint_id===void 0&&a?.pendingWrites!==void 0&&a.pendingWrites.length>0){let e=Wl(o,a.pendingWrites,this.nodes,p,a.config,!0,{store:this.store,checkpointer:this.checkpointer,step:(a.metadata?.step??-1)+1}),t=(a.pendingWrites??[]).filter(e=>e[0]===Js).map(e=>e.slice(1));t.length>0&&Hl(a.checkpoint,p,[{name:bs,writes:t,triggers:[]}],void 0,this.triggerToNodes);for(let[t,n,r]of a.pendingWrites)[`__error__`,`__interrupt__`,`__scheduled__`].includes(n)||e[t]===void 0||e[t].writes.push([n,r]);let n=Object.values(e).filter(e=>e.writes.length>0);n.length>0&&Hl(o,p,n,void 0,this.triggerToNodes)}let m=Object.values(o.versions_seen).map(e=>Object.values(e)).flat().find(e=>!!e),h=[];if(t.length===1){let{values:e,asNode:n,taskId:r}=t[0];if(n===void 0&&Object.keys(this.nodes).length===1)[n]=Object.keys(this.nodes);else if(n===void 0&&m===void 0)typeof this.inputChannels==`string`&&this.nodes[this.inputChannels]!==void 0&&(n=this.inputChannels);else if(n===void 0){let e=Object.entries(o.versions_seen).map(([e,t])=>Object.values(t).map(t=>[t,e])).flat().filter(([e,t])=>t!==B).sort(([e],[t])=>Qo(e,t));e&&(e.length===1?n=e[0][1]:e[e.length-1][0]!==e[e.length-2][0]&&(n=e[e.length-1][1]))}if(n===void 0)throw new P(`Ambiguous update, specify "asNode"`);h.push({values:e,asNode:n,taskId:r})}else for(let{asNode:e,values:n,taskId:r}of t){if(e==null)throw new P(`"asNode" is required when applying multiple updates`);h.push({values:n,asNode:e,taskId:r})}let g=[];for(let{asNode:e,values:t,taskId:n}of h){if(this.nodes[e]===void 0)throw new P(`Node "${e.toString()}" does not exist`);let r=this.nodes[e].getWriters();if(!r.length)throw new P(`No writers found for node "${e.toString()}"`);g.push({name:e,input:t,proc:r.length>1?qe.from(r,{omitSequenceTags:!0}):r[0],writes:[],triggers:[B],id:n??$n(`__interrupt__`,o.id),writers:[]})}for(let e of g)await e.proc.invoke(e.input,ke({...r,store:r?.store??this.store},{runName:r.runName??`${this.getName()}UpdateState`,configurable:{[Cs]:t=>e.writes.push(...t),[Ts]:(t,n=!1)=>zl(o,p,e,t,n)}}));for(let e of g){let t=e.writes.filter(e=>e[0]!==Ks);a!==void 0&&t.length>0&&await n.putWrites(l,t,e.id)}Hl(o,p,g,n.getNextVersion.bind(this.checkpointer),this.triggerToNodes);let _=Tl(s,o.channel_versions),v=await n.put(l,fs(o,p,c+1),{source:`update`,step:c+1,parents:a?.metadata?.parents??{}},_);for(let e of g){let t=e.writes.filter(e=>e[0]===Ks);t.length>0&&await n.putWrites(v,t,e.id)}return Ol(v,a?a.metadata:void 0)},a=e;for(let{updates:e}of t)a=await i(a,e);return a}async updateState(e,t,n){return this.bulkUpdateState(e,[{updates:[{values:t,asNode:n}]}])}_defaults(e){let{debug:t,streamMode:n,inputKeys:r,outputKeys:i,interruptAfter:a,interruptBefore:o,...s}=e,c=!0,l=t===void 0?this.debug:t,u=i;u===void 0?u=this.streamChannelsAsIs:Iu(u,this.channels);let d=r;d===void 0?d=this.inputChannels:Iu(d,this.channels);let f=o??this.interruptBefore??[],p=a??this.interruptAfter??[],m;n===void 0?(m=e.configurable?.__pregel_task_id===void 0?this.streamMode:[`values`],c=!0):(m=Array.isArray(n)?n:[n],c=typeof n==`string`);let h;if(this.checkpointer===!1)h=void 0;else if(e!==void 0&&e.configurable?.__pregel_checkpointer!==void 0)h=e.configurable[Es];else if(this.checkpointer===!0)throw Error(`checkpointer: true cannot be used for root graphs.`);else h=this.checkpointer;let g=e.store??this.store,_=e.cache??this.cache;if(e.durability!=null&&e.checkpointDuring!=null)throw Error("Cannot use both `durability` and `checkpointDuring` at the same time.");let v=(()=>{if(e.checkpointDuring!=null)return e.checkpointDuring===!1?`exit`:`async`})(),y=e.durability??v??e?.configurable?.__pregel_durability??`async`;return[l,m,d,u,s,f,p,h,g,c,_,y]}async stream(e,t){let n=new AbortController,r={recursionLimit:this.config?.recursionLimit,...t,signal:kl(t?.signal,n.signal).signal},i=await super.stream(e,r);return new ou(t?.encoding===`text/event-stream`?mu(i):i,n)}streamEvents(e,t,n){let r=new AbortController,i={recursionLimit:this.config?.recursionLimit,...t,callbacks:Al(this.config?.callbacks,t?.callbacks),signal:kl(t?.signal,r.signal).signal};return new ou(super.streamEvents(e,i,n),r)}async _validateInput(e){return e}async _validateContext(e){return e}async*_streamIterator(e,t){let n=`version`in(t??{})?void 0:t?.encoding??void 0,r=t?.subgraphs,i=ic(this.config,t);if(i.recursionLimit===void 0||i.recursionLimit<1)throw Error(`Passed "recursionLimit" must be at least 1.`);if(this.checkpointer!==void 0&&this.checkpointer!==!1&&i.configurable===void 0)throw Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`);let a=await this._validateInput(e),{runId:o,...s}=i,[c,l,,u,d,f,p,m,h,g,_,v]=this._defaults(s);d.context===void 0?d.configurable=await this._validateContext(d.configurable):d.context=await this._validateContext(d.context);let y=new su({modes:new Set(l)});if(this.checkpointer===!0){d.configurable??={};let e=d.configurable.checkpoint_ns??``;d.configurable[Is]=e.split(`|`).map(e=>e.split(`:`)[0]).join(`|`)}if(l.includes(`messages`)){let e=new Su(e=>y.push(e)),{callbacks:t}=d;if(t===void 0)d.callbacks=[e];else if(Array.isArray(t))d.callbacks=t.concat(e);else{let n=t.copy();n.addHandler(e,!0),d.callbacks=n}}d.writer??=e=>{if(!l.includes(`custom`))return;let t=(ac()?.configurable?.[Is])?.split(`|`).slice(0,-1);y.push([t??[],`custom`,e])},d.interrupt??=this.userInterrupt??Qc;let b=await(await dt(d))?.handleChainStart(this.toJSON(),El(e,`input`),o,void 0,void 0,void 0,d?.runName??this.getName()),x=us(this.channels),S,ee,te=(async()=>{try{S=await bu.initialize({input:a,config:d,checkpointer:m,nodes:this.nodes,channelSpecs:x,outputKeys:u,streamKeys:this.streamChannelsAsIs,store:h,cache:_,stream:y,interruptAfter:p,interruptBefore:f,manager:b,debug:this.debug,triggerToNodes:this.triggerToNodes,durability:v});let e=new Mu({loop:S,nodeFinished:d.configurable?.[Ls]});t?.subgraphs&&(S.config.configurable={...S.config.configurable,[ks]:S.stream}),await this._runLoop({loop:S,runner:e,debug:c,config:d}),v===`sync`&&await Promise.all(S?.checkpointerPromises??[])}catch(e){ee=e}finally{try{S&&(await S.store?.stop(),await S.cache?.stop()),await Promise.all(S?.checkpointerPromises??[])}catch(e){ee??=e}ee?y.error(ee):y.close()}})();try{for await(let e of y){if(e===void 0)throw Error(`Data structure error.`);let[t,i,a]=e;if(l.includes(i)){if(n===`text/event-stream`){r?yield[t,i,a]:yield[null,i,a];continue}r&&!g?yield[t,i,a]:g?r?yield[t,a]:yield a:yield[i,a]}}}catch(e){throw await b?.handleChainError(ee),e}finally{await te}await b?.handleChainEnd(S?.output??{},o,void 0,void 0,void 0)}async invoke(e,t){let n=t?.streamMode??`values`,r={...t,outputKeys:t?.outputKeys??this.outputChannels,streamMode:n,encoding:void 0},i=[],a=await this.stream(e,r),o=[],s;for await(let e of a)n===`values`?$s(e)?o.push(e[B]):s=e:i.push(e);if(n===`values`){if(o.length>0){let e=o.flat(1);if(s==null)return{[B]:e};if(typeof s==`object`)return{...s,[B]:e}}return s}return i}async _runLoop(e){let{loop:t,runner:n,debug:r,config:i}=e,a;try{for(;await t.tick({inputKeys:this.inputChannels});){for(let{task:e}of await t._matchCachedWrites())t._outputWrites(e.id,e.writes,!0);r&&ru(t.checkpointMetadata.step,t.channels,this.streamChannelsList),r&&iu(t.step,Object.values(t.tasks)),await n.tick({timeout:this.stepTimeout,retryPolicy:this.retryPolicy,onStepWrite:(e,t)=>{r&&au(e,t,this.streamChannelsList)},maxConcurrency:i.maxConcurrency,signal:i.signal})}if(t.status===`out_of_steps`)throw new Vn([`Recursion limit of ${i.recursionLimit} reached`,`without hitting a stop condition. You can increase the`,`limit by setting the "recursionLimit" config key.`].join(` `),{lc_error_code:`GRAPH_RECURSION_LIMIT`})}catch(e){if(a=e,!await t.finishAndHandleError(a))throw e}finally{a===void 0&&await t.finishAndHandleError()}}async clearCache(){await this.cache?.clear([])}},Vu=class e extends cs{lc_graph_name=`EphemeralValue`;guard;value=[];constructor(e=!0){super(),this.guard=e}fromCheckpoint(t){let n=new e(this.guard);return t!==void 0&&(n.value=[t]),n}update(e){if(e.length===0){let e=this.value.length>0;return this.value=[],e}if(e.length!==1&&this.guard)throw new P(`EphemeralValue can only receive one value per step.`);return this.value=[e[e.length-1]],!0}get(){if(this.value.length===0)throw new N;return this.value[0]}checkpoint(){if(this.value.length===0)throw new N;return this.value[0]}isAvailable(){return this.value.length!==0}},Hu=class{path;ends;constructor(e){E.isRunnable(e.path)?this.path=e.path:this.path=ut(e.path).withConfig({runName:`Branch`}),this.ends=Array.isArray(e.pathMap)?e.pathMap.reduce((e,t)=>(e[t]=t,e),{}):e.pathMap}run(e,t){return Y.registerWriter(new $c({name:`<branch_run>`,trace:!1,func:async(n,r)=>{try{return await this._route(n,r,e,t)}catch(e){throw e.name===Wn.unminifiable_name&&console.warn(`[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.
|
|
27
27
|
NodeInterrupt should only be thrown inside a node, not in edge conditions.`),e}}}))}async _route(e,t,n,r){let i=await this.path.invoke(r?r(t):e,t);Array.isArray(i)||(i=[i]);let a;if(a=this.ends?i.map(e=>U(e)?e:this.ends[e]):i,a.some(e=>!e))throw Error(`Branch condition returned unknown or null destination`);if(a.filter(U).some(e=>e.node===`__end__`))throw new P(`Cannot send a packet to the END node`);return await n(a,t)??e}},Uu=class{nodes;edges;branches;entryPoint;compiled=!1;constructor(){this.nodes={},this.edges=new Set,this.branches={}}warnIfCompiled(e){this.compiled&&console.warn(e)}get allEdges(){return this.edges}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`)throw Error(`Node \`${e}\` is reserved.`);let n=ut(t);this.nodes[e]={runnable:n,metadata:r?.metadata,subgraphs:gl(n)?[n]:r?.subgraphs,ends:r?.ends}}return this}addEdge(e,t){if(this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e===`__end__`)throw Error(`END cannot be a start node`);if(t===`__start__`)throw Error(`START cannot be an end node`);if(Array.from(this.edges).some(([t])=>t===e)&&!(`channels`in this))throw Error(`Already found path for ${e}. For multiple edges, use StateGraph.`);return this.edges.add([e,t]),this}addConditionalEdges(e,t,n){let r=typeof e==`object`?e:{source:e,path:t,pathMap:n};if(this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`),!E.isRunnable(r.path)){let e=Array.isArray(r.pathMap)?r.pathMap.join(`,`):Object.keys(r.pathMap??{}).join(`,`);r.path=ut(r.path).withConfig({runName:`Branch<${r.source}${e===``?``:`,${e}`}>`.slice(0,63)})}let i=r.path.getName()===`RunnableLambda`?`condition`:r.path.getName();if(this.branches[r.source]&&this.branches[r.source][i])throw Error(`Condition \`${i}\` already present for node \`${e}\``);return this.branches[r.source]??={},this.branches[r.source][i]=new Hu(r),this}setEntryPoint(e){return this.warnIfCompiled(`Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph.`),this.addEdge(R,e)}setFinishPoint(e){return this.warnIfCompiled(`Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph.`),this.addEdge(e,z)}compile({checkpointer:e,interruptBefore:t,interruptAfter:n,name:r}={}){this.validate([...Array.isArray(t)?t:[],...Array.isArray(n)?n:[]]);let i=new Wu({builder:this,checkpointer:e,interruptAfter:n,interruptBefore:t,autoValidate:!1,nodes:{},channels:{[R]:new Vu,[z]:new Vu},inputChannels:R,outputChannels:z,streamChannels:[],streamMode:`values`,name:r});for(let[e,t]of Object.entries(this.nodes))i.attachNode(e,t);for(let[e,t]of this.edges)i.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))i.attachBranch(e,n,r);return i.validate()}validate(e){let t=new Set([...this.allEdges].map(([e,t])=>e));for(let[e]of Object.entries(this.branches))t.add(e);for(let e of t)if(e!==`__start__`&&!(e in this.nodes))throw Error(`Found edge starting at unknown node \`${e}\``);let n=new Set([...this.allEdges].map(([e,t])=>t));for(let[e,t]of Object.entries(this.branches))for(let r of Object.values(t))if(r.ends!=null)for(let e of Object.values(r.ends))n.add(e);else{n.add(z);for(let t of Object.keys(this.nodes))t!==e&&n.add(t)}for(let e of Object.values(this.nodes))for(let t of e.ends??[])n.add(t);for(let e of Object.keys(this.nodes))if(!n.has(e))throw new Xn([`Node \`${e}\` is not reachable.`,``,`If you are returning Command objects from your node,`,`make sure you are passing names of potential destination nodes as an "ends" array`,`into ".addNode(..., { ends: ["node1", "node2"] })".`].join(`
|
|
28
28
|
`),{lc_error_code:`UNREACHABLE_NODE`});for(let e of n)if(e!==`__end__`&&!(e in this.nodes))throw Error(`Found edge ending at unknown node \`${e}\``);if(e){for(let t of e)if(!(t in this.nodes))throw Error(`Interrupt node \`${t}\` is not present`)}this.compiled=!0}},Wu=class extends Bu{builder;constructor({builder:e,...t}){super(t),this.builder=e}attachNode(e,t){this.channels[e]=new Vu,this.nodes[e]=new ml({channels:[],triggers:[],metadata:t.metadata,subgraphs:t.subgraphs,ends:t.ends}).pipe(t.runnable).pipe(new Y([{channel:e,value:sl}],[V])),this.streamChannels.push(e)}attachEdge(e,t){if(t===`__end__`){if(e===`__start__`)throw Error(`Cannot have an edge from START to END`);this.nodes[e].writers.push(new Y([{channel:z,value:sl}],[V]))}else this.nodes[t].triggers.push(e),this.nodes[t].channels.push(e)}attachBranch(e,t,n){e===`__start__`&&!this.nodes.__start__&&(this.nodes[R]=Ru.subscribeTo(R,{tags:[V]})),this.nodes[e].pipe(n.run(n=>new Y(n.map(n=>U(n)?n:{channel:n===`__end__`?z:`branch:${e}:${t}:${n}`,value:sl}),[V])));let r=n.ends?Object.values(n.ends):Object.keys(this.nodes);for(let n of r)if(n!==`__end__`){let r=`branch:${e}:${t}:${n}`;this.channels[r]=new Vu,this.nodes[n].triggers.push(r),this.nodes[n].channels.push(r)}}async getGraphAsync(e){let t=e?.xray,n=new vt,r={[R]:n.addNode({schema:Ot()},R)},i={},a={};t&&(a=Object.fromEntries((await tl(this.getSubgraphsAsync())).filter(e=>Gu(e[1]))));function o(e,t,a,o=!1){if(t===`__end__`&&i.__end__===void 0&&(i[z]=n.addNode({schema:Ot()},z)),r[e]!==void 0){if(i[t]===void 0)throw Error(`End node ${t} not found!`);return n.addEdge(r[e],i[t],a===t?void 0:a,o)}}for(let[o,s]of Object.entries(this.builder.nodes)){let c=X(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):await a[o].getGraphAsync({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!be(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let s=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of s)o(X(e),X(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[X(e),X(e)])),[z]:z};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))o(X(e),X(r),n,!0)}}for(let[e,t]of Object.entries(this.builder.nodes))if(t.ends!==void 0)for(let n of t.ends)o(X(e),X(n),void 0,!0);return n}getGraph(e){let t=e?.xray,n=new vt,r={[R]:n.addNode({schema:Ot()},R)},i={},a={};t&&(a=Object.fromEntries(nl(this.getSubgraphs()).filter(e=>Gu(e[1]))));function o(e,t,a,o=!1){return t===`__end__`&&i.__end__===void 0&&(i[z]=n.addNode({schema:Ot()},z)),n.addEdge(r[e],i[t],a===t?void 0:a,o)}for(let[o,s]of Object.entries(this.builder.nodes)){let c=X(o),l=s.runnable,u=s.metadata??{};if(this.interruptBefore?.includes(o)&&this.interruptAfter?.includes(o)?u.__interrupt=`before,after`:this.interruptBefore?.includes(o)?u.__interrupt=`before`:this.interruptAfter?.includes(o)&&(u.__interrupt=`after`),t){let s=typeof t==`number`?t-1:t,d=a[o]===void 0?l.getGraph(e):a[o].getGraph({...e,xray:s});if(d.trimFirstNode(),d.trimLastNode(),Object.keys(d.nodes).length>1){let[e,t]=n.extend(d,c);if(e===void 0)throw Error(`Could not extend subgraph "${o}" due to missing entrypoint.`);function a(e){return e?e.lc_runnable:!1}function s(e,t){if(e!==void 0&&!be(e))return e;if(a(t))try{let e=t.getName();return e=e.startsWith(`Runnable`)?e.slice(8):e,e}catch{return t.getName()}else return t.name??`UnknownSchema`}t!==void 0&&(r[c]={name:s(t.id,t.data),...t}),i[c]={name:s(e.id,e.data),...e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}else{let e=n.addNode(l,c,u);r[c]=e,i[c]=e}}let s=[...this.builder.allEdges].sort(([e],[t])=>e<t?-1:+(t>e));for(let[e,t]of s)o(X(e),X(t));for(let[e,t]of Object.entries(this.builder.branches)){let n={...Object.fromEntries(Object.keys(this.builder.nodes).filter(t=>t!==e).map(e=>[X(e),X(e)])),[z]:z};for(let r of Object.values(t)){let t;t=r.ends===void 0?n:r.ends;for(let[n,r]of Object.entries(t))o(X(e),X(r),n,!0)}}return n}};function Gu(e){return typeof e.attachNode==`function`&&typeof e.attachEdge==`function`}function X(e){return e===`subgraph`?`"${e}"`:e}function Ku(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`validate`in e[`~standard`]}function qu(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`]!==null&&`jsonSchema`in e[`~standard`]}function Ju(e){if(qu(e))try{return e[`~standard`].jsonSchema.input({target:`draft-07`})}catch{return}}function Yu(e){if(e!=null&&Ku(e))try{let t=e[`~standard`].validate(void 0);if(t&&typeof t==`object`&&!(`then`in t&&typeof t.then==`function`)){let e=t;if(!e.issues){let t=e.value;return()=>t}}}catch{}}var Xu=Symbol.for(`langgraph.channel.missing`),Zu=class e extends cs{lc_graph_name=`UntrackedValue`;guard;_value=Xu;initialValueFactory;constructor(e){super(),this.guard=e?.guard??!0,this.initialValueFactory=e?.initialValueFactory,this.initialValueFactory&&(this._value=this.initialValueFactory())}fromCheckpoint(t){return new e({guard:this.guard,initialValueFactory:this.initialValueFactory})}update(e){if(e.length===0)return!1;if(e.length!==1&&this.guard)throw new P(`UntrackedValue(guard=true) can receive only one value per step. Use guard=false if you want to store any one of multiple values.`,{lc_error_code:`INVALID_CONCURRENT_GRAPH_UPDATE`});return this._value=e[e.length-1],!0}get(){if(this._value===Xu)throw new N;return this._value}checkpoint(){}isAvailable(){return this._value!==Xu}},Qu=Symbol.for(`langgraph.state.reduced_value`),$u=class{[Qu]=!0;valueSchema;inputSchema;reducer;jsonSchemaExtra;constructor(e,t){this.reducer=t.reducer,this.jsonSchemaExtra=t.jsonSchemaExtra,this.valueSchema=e,this.inputSchema=`inputSchema`in t?t.inputSchema:e,this.jsonSchemaExtra=t.jsonSchemaExtra}static isInstance(e){return typeof e==`object`&&!!e&&Qu in e&&e[Qu]===!0}},ed=Symbol.for(`langgraph.state.untracked_value`),td=class{[ed]=!0;schema;guard;constructor(e,t){this.schema=e,this.guard=t?.guard??!0}static isInstance(e){return typeof e==`object`&&!!e&&ed in e}},nd=(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e)),rd=class e extends cs{lc_graph_name=`NamedBarrierValue`;names;seen;constructor(e){super(),this.names=e,this.seen=new Set}fromCheckpoint(t){let n=new e(this.names);return t!==void 0&&(n.seen=new Set(t)),n}update(e){let t=!1;for(let n of e)if(this.names.has(n))this.seen.has(n)||(this.seen.add(n),t=!0);else throw new P(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!nd(this.names,this.seen))throw new N}checkpoint(){return[...this.seen]}consume(){return this.seen&&this.names&&nd(this.seen,this.names)?(this.seen=new Set,!0):!1}isAvailable(){return!!this.names&&nd(this.names,this.seen)}},id=class e extends cs{lc_graph_name=`NamedBarrierValueAfterFinish`;names;seen;finished;constructor(e){super(),this.names=e,this.seen=new Set,this.finished=!1}fromCheckpoint(t){let n=new e(this.names);if(t!==void 0){let[e,r]=t;n.seen=new Set(e),n.finished=r}return n}update(e){let t=!1;for(let n of e)if(this.names.has(n)&&!this.seen.has(n))this.seen.add(n),t=!0;else if(!this.names.has(n))throw new P(`Value ${JSON.stringify(n)} not in names ${JSON.stringify(this.names)}`);return t}get(){if(!this.finished||!nd(this.names,this.seen))throw new N}checkpoint(){return[[...this.seen],this.finished]}consume(){return this.finished&&this.seen&&this.names&&nd(this.seen,this.names)?(this.seen=new Set,this.finished=!1,!0):!1}finish(){return!this.finished&&this.names&&nd(this.names,this.seen)?(this.finished=!0,!0):!1}isAvailable(){return this.finished&&!!this.names&&nd(this.names,this.seen)}},ad=Symbol.for(`langgraph.state.state_schema`),Z=class{[ad]=!0;constructor(e){this.fields=e}getChannels(){let e={};for(let[t,n]of Object.entries(this.fields))if($u.isInstance(n)){let r=Yu(n.valueSchema);e[t]=new ms(n.reducer,r)}else if(td.isInstance(n)){let r=n.schema?Yu(n.schema):void 0;e[t]=new Zu({guard:n.guard,initialValueFactory:r})}else if(Ku(n))e[t]=new hs(Yu(n));else throw Error(`Invalid state field "${t}": must be a schema, ReducedValue, UntrackedValue, or ManagedValue`);return e}getJsonSchema(){let e={},t=[];for(let[n,r]of Object.entries(this.fields)){let i;if($u.isInstance(r)?(i=Ju(r.valueSchema),r.jsonSchemaExtra&&(i={...i??{},...r.jsonSchemaExtra})):td.isInstance(r)?i=r.schema?Ju(r.schema):void 0:Ku(r)&&(i=Ju(r)),i){e[n]=i;let a=!1;a=$u.isInstance(r)?Yu(r.valueSchema)!==void 0:td.isInstance(r)?r.schema?Yu(r.schema)!==void 0:!1:Yu(r)!==void 0,a||t.push(n)}}return{type:`object`,properties:e,required:t.length>0?t:void 0}}getInputJsonSchema(){let e={};for(let[t,n]of Object.entries(this.fields)){let r;$u.isInstance(n)?r=Ju(n.inputSchema):td.isInstance(n)?r=n.schema?Ju(n.schema):void 0:Ku(n)&&(r=Ju(n)),r&&(e[t]=r)}return{type:`object`,properties:e}}getChannelKeys(){return Object.entries(this.fields).map(([e])=>e)}getAllKeys(){return Object.keys(this.fields)}async validateInput(e){if(typeof e!=`object`||!e)return e;let t={};for(let[n,r]of Object.entries(e)){let e=this.fields[n];if(e===void 0){t[n]=r;continue}let i;if($u.isInstance(e)?i=e.inputSchema:td.isInstance(e)?i=e.schema:Ku(e)&&(i=e),i){let e=await i[`~standard`].validate(r);if(e.issues)throw Error(`Validation failed for field "${n}": ${JSON.stringify(e.issues)}`);t[n]=e.value}else t[n]=r}return t}static isInstance(e){return typeof e==`object`&&!!e&&ad in e&&e[ad]===!0}},od=`__remove_all__`;function sd(e,t){let n=Array.isArray(e)?e:[e],r=Array.isArray(t)?t:[t],i=n.map(g),a=r.map(g);for(let e of i)(e.id===null||e.id===void 0)&&(e.id=te(),e.lc_kwargs.id=e.id);let o;for(let e=0;e<a.length;e+=1){let t=a[e];(t.id===null||t.id===void 0)&&(t.id=te(),t.lc_kwargs.id=t.id),lt.isInstance(t)&&t.id===`__remove_all__`&&(o=e)}if(o!=null)return a.slice(o+1);let s=[...i],c=new Map(s.map((e,t)=>[e.id,t])),l=new Set;for(let e of a){let t=c.get(e.id);if(t!==void 0)lt.isInstance(e)?l.add(e.id):(l.delete(e.id),s[t]=e);else{if(lt.isInstance(e))throw Error(`Attempting to delete a message with an ID that doesn't exist ('${e.id}')`);c.set(e.id,s.length),s.push(e)}}return s.filter(e=>!l.has(e.id))}var cd=new $u(kt().default(()=>[]),{inputSchema:kt(),reducer:sd,jsonSchemaExtra:{langgraph_type:`messages`,description:`A list of chat messages`}}),ld=new class{_map=new Map;_extensionCache=new Map;get(e){return this._map.get(e)}extend(e,t){let n=this.get(e);this._map.set(e,t(n))}remove(e){return this._map.delete(e),this}has(e){return this._map.has(e)}getChannelsForSchema(e){let t={},n=Ve(e);for(let[e,r]of Object.entries(n)){let n=this.get(r);n?.reducer?t[e]=new ms(n.reducer.fn,n.default):t[e]=new hs(n?.default)}return t}getExtendedChannelSchemas(e,t){if(Object.keys(t).length===0)return e;let n=Object.entries(t).filter(([,e])=>e===!0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}:${t}`).join(`|`),i=this._extensionCache.get(n)??new Map;if(i.has(e))return i.get(e);let a=e;if(t.withReducerSchema||t.withJsonSchemaExtrasAsDescription){let n=Object.entries(Ve(e)).map(([e,n])=>{let i=this.get(n),a=t.withReducerSchema?i?.reducer?.schema??n:n;if(t.withJsonSchemaExtrasAsDescription&&i?.jsonSchemaExtra){let e=r(a)??r(n),t=JSON.stringify({...i.jsonSchemaExtra,description:e});a=a.describe(`lg:${t}`)}return[e,a]});a=l(e,Object.fromEntries(n)),Me(a)&&(a._def.unknownKeys=`strip`)}return t.asPartial&&(a=b(a)),i.set(e,a),this._extensionCache.set(n,i),a}};function ud(e,t){if(t.reducer&&!t.default){let n=ae(e);n!=null&&(t.default=n)}if(t.reducer){let n=Object.assign(e,{lg_reducer_schema:t.reducer?.schema??e});return ld.extend(n,()=>t),n}else return ld.extend(e,()=>t),e}function dd(e){return e==null?!1:!!(Z.isInstance(e)||_(e)||typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`||typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0&&Object.values(e).every(e=>typeof e==`function`||ss(e)))}function fd(e){if(typeof e!=`object`||!e)return!1;let t=e,n=`state`in t&&dd(t.state),r=`stateSchema`in t&&dd(t.stateSchema),i=`input`in t&&dd(t.input);return!(!n&&!r&&!i||`input`in t&&t.input!=null&&!dd(t.input)||`output`in t&&t.output!=null&&!dd(t.output))}var pd=`__root__`,md=Symbol.for(`langgraph.state.partial`),hd=class extends Uu{channels={};waitingEdges=new Set;_schemaDefinition;_schemaRuntimeDefinition;_inputDefinition;_inputRuntimeDefinition;_outputDefinition;_outputRuntimeDefinition;_schemaDefinitions=new Map;_metaRegistry=ld;_configSchema;_configRuntimeSchema;_interrupt;_writer;constructor(e,t){super();let n=this._normalizeToStateGraphInit(e,t),r=n.state??n.stateSchema??n.input;if(!r)throw new Zn;let i=this._getChannelsFromSchema(r);this._schemaDefinition=i,(Z.isInstance(r)||_(r))&&(this._schemaRuntimeDefinition=r),n.input&&(Z.isInstance(n.input)||_(n.input))?this._inputRuntimeDefinition=n.input:this._inputRuntimeDefinition=md,n.output&&(Z.isInstance(n.output)||_(n.output))?this._outputRuntimeDefinition=n.output:this._outputRuntimeDefinition=this._schemaRuntimeDefinition;let a=n.input?this._getChannelsFromSchema(n.input):i,o=n.output?this._getChannelsFromSchema(n.output):i;this._inputDefinition=a,this._outputDefinition=o,this._addSchema(this._schemaDefinition),this._addSchema(this._inputDefinition),this._addSchema(this._outputDefinition),n.context&&_(n.context)&&(this._configRuntimeSchema=n.context),this._interrupt=n.interrupt,this._writer=n.writer}_normalizeToStateGraphInit(e,t){if(fd(e)){if(_(t)||_s.isInstance(t))return{...e,context:t};let n=t;return{...e,input:e.input??n?.input,output:e.output??n?.output,context:e.context??n?.context,interrupt:e.interrupt??n?.interrupt,writer:e.writer??n?.writer,nodes:e.nodes??n?.nodes}}if(dd(e)){if(_(t)||_s.isInstance(t))return{state:e,context:t};let n=t;return{state:e,input:n?.input,output:n?.output,context:n?.context,interrupt:n?.interrupt,writer:n?.writer,nodes:n?.nodes}}if(vd(e))return{state:gd(e.channels)};throw new Zn}_getChannelsFromSchema(e){if(Z.isInstance(e))return e.getChannels();if(_(e))return this._metaRegistry.getChannelsForSchema(e);if(typeof e==`object`&&`lc_graph_name`in e&&e.lc_graph_name===`AnnotationRoot`)return e.spec;if(typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length>0)return e;throw new Zn(`Invalid schema type. Expected StateSchema, Zod object, AnnotationRoot, or StateDefinition.`)}get allEdges(){return new Set([...this.edges,...Array.from(this.waitingEdges).flatMap(([e,t])=>e.map(e=>[e,t]))])}_addSchema(e){if(!this._schemaDefinitions.has(e)){this._schemaDefinitions.set(e,e);for(let[t,n]of Object.entries(e)){let e;if(e=typeof n==`function`?n():n,this.channels[t]!==void 0){if(!this.channels[t].equals(e)&&e.lc_graph_name!==`LastValue`)throw Error(`Channel "${t}" already exists with a different type.`)}else this.channels[t]=e}}}addNode(...e){function t(e){return e.length>=1&&typeof e[0]!=`string`}let n=t(e)?Array.isArray(e[0])?e[0]:Object.entries(e[0]).map(([e,t])=>[e,t]):[[e[0],e[1],e[2]]];if(n.length===0)throw Error("No nodes provided in `addNode`");for(let[e,t,r]of n){if(e in this.channels)throw Error(`${e} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`);for(let t of[`|`,`:`])if(e.includes(t))throw Error(`"${t}" is a reserved character and is not allowed in node names.`);if(this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`),e in this.nodes)throw Error(`Node \`${e}\` already present.`);if(e===`__end__`||e===`__start__`)throw Error(`Node \`${e}\` is reserved.`);let n=this._schemaDefinition;r?.input!==void 0&&(n=this._getChannelsFromSchema(r.input)),this._addSchema(n);let i;i=E.isRunnable(t)?t:typeof t==`function`?new $c({func:t,name:e,trace:!1}):ut(t);let a=r?.cachePolicy;typeof a==`boolean`&&(a=a?{}:void 0);let o={runnable:i,retryPolicy:r?.retryPolicy,cachePolicy:a,metadata:r?.metadata,input:n??this._schemaDefinition,subgraphs:gl(i)?[i]:r?.subgraphs,ends:r?.ends,defer:r?.defer};this.nodes[e]=o}return this}addEdge(e,t){if(typeof e==`string`)return super.addEdge(e,t);this.compiled&&console.warn(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`);for(let t of e){if(t===`__end__`)throw Error(`END cannot be a start node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`)}if(t===`__end__`)throw Error(`END cannot be an end node`);if(!Object.keys(this.nodes).some(e=>e===t))throw Error(`Need to add a node named "${t}" first`);return this.waitingEdges.add([e,t]),this}addSequence(e){let t=Array.isArray(e)?e:Object.entries(e);if(t.length===0)throw Error(`Sequence requires at least one node.`);let n;for(let[e,r,i]of t){if(e in this.nodes)throw Error(`Node names must be unique: node with the name "${e}" already exists.`);let t=e;this.addNode(t,r,i),n!=null&&this.addEdge(n,t),n=t}return this}compile({checkpointer:e,store:t,cache:n,interruptBefore:r,interruptAfter:i,name:a,description:o}={}){this.validate([...Array.isArray(r)?r:[],...Array.isArray(i)?i:[]]);let s=Object.keys(this._schemaDefinitions.get(this._outputDefinition)),c=s.length===1&&s[0]===pd?pd:s,l=Object.keys(this.channels),u=l.length===1&&l[0]===pd?pd:l,d=this._interrupt,f=new _d({builder:this,checkpointer:e,interruptAfter:i,interruptBefore:r,autoValidate:!1,nodes:{},channels:{...this.channels,[R]:new Vu},inputChannels:R,outputChannels:c,streamChannels:u,streamMode:`updates`,store:t,cache:n,name:a,description:o,userInterrupt:d});f.attachNode(R);for(let[e,t]of Object.entries(this.nodes))f.attachNode(e,t);f.attachBranch(R,Ws,bd(),{withReader:!1});for(let[e]of Object.entries(this.nodes))f.attachBranch(e,Ws,bd(),{withReader:!1});for(let[e,t]of this.edges)f.attachEdge(e,t);for(let[e,t]of this.waitingEdges)f.attachEdge(e,t);for(let[e,t]of Object.entries(this.branches))for(let[n,r]of Object.entries(t))f.attachBranch(e,n,r);return f.validate()}};function gd(e){let t={};for(let[n,r]of Object.entries(e))t[n]=ys(r);return t}var _d=class extends Wu{description;_metaRegistry=ld;constructor({description:e,...t}){super(t),this.description=e}attachNode(e,t){let n;n=e===`__start__`?Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([e])=>e):Object.keys(this.builder.channels);function r(e){if(G(e))return e.graph===W.PARENT?null:e._updateAsTuples();if(Array.isArray(e)&&e.length>0&&e.some(e=>G(e))){let t=[];for(let n of e)if(G(n)){if(n.graph===W.PARENT)continue;t.push(...n._updateAsTuples())}else t.push([pd,n]);return t}else if(e!=null)return[[pd,e]];return null}let i=e;function a(e){if(!e)return null;if(G(e))return e.graph===W.PARENT?null:e._updateAsTuples().filter(([e])=>n.includes(e));if(Array.isArray(e)&&e.length>0&&e.some(G)){let t=[];for(let r of e)if(G(r)){if(r.graph===W.PARENT)continue;t.push(...r._updateAsTuples().filter(([e])=>n.includes(e)))}else{let e=a(r);e&&t.push(...e??[])}return t}else if(typeof e==`object`&&!Array.isArray(e))return Object.entries(e).filter(([e])=>n.includes(e));else{let t=Array.isArray(e)?`array`:typeof e;throw new P(`Expected node "${i.toString()}" to return an object or an array containing at least one Command object, received ${t}`,{lc_error_code:`INVALID_GRAPH_NODE_RETURN_VALUE`})}}let o=[{value:sl,mapper:new $c({func:n.length&&n[0]===pd?r:a,trace:!1,recurse:!1})}];if(e===`__start__`)this.nodes[e]=new ml({tags:[V],triggers:[R],channels:[R],writers:[new Y(o,[V])]});else{let n=t?.input??this.builder._schemaDefinition,r=Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(n)).map(e=>[e,e])),i=Object.keys(r).length===1&&pd in r,a=`branch:to:${e}`;this.channels[a]=t?.defer?new gs:new Vu(!1),this.nodes[e]=new ml({triggers:[a],channels:i?Object.keys(r):r,writers:[new Y(o,[V])],mapper:i?void 0:e=>Object.fromEntries(Object.entries(e).filter(([e])=>e in r)),bound:t?.runnable,metadata:t?.metadata,retryPolicy:t?.retryPolicy,cachePolicy:t?.cachePolicy,subgraphs:t?.subgraphs,ends:t?.ends})}}attachEdge(e,t){if(t!==`__end__`){if(typeof e==`string`)this.nodes[e].writers.push(new Y([{channel:`branch:to:${t}`,value:null}],[V]));else if(Array.isArray(e)){let n=`join:${e.join(`+`)}:${t}`;this.channels[n]=this.builder.nodes[t].defer?new id(new Set(e)):new rd(new Set(e)),this.nodes[t].triggers.push(n);for(let t of e)this.nodes[t].writers.push(new Y([{channel:n,value:t}],[V]))}}}attachBranch(e,t,n,r={withReader:!0}){this.nodes[e].writers.push(n.run(async(t,n)=>{let r=t.filter(e=>e!==z);if(!r.length)return;let i=r.map(t=>U(t)?t:{channel:t===`__end__`?t:`branch:to:${t}`,value:e});await Y.doWrite({...n,tags:(n.tags??[]).concat([V])},i)},r.withReader?e=>fl.doRead(e,this.streamChannels??this.outputChannels,!0):void 0))}async _validateInput(e){if(e==null)return e;let t=this.builder._inputRuntimeDefinition,n=this.builder._schemaRuntimeDefinition;if(Z.isInstance(t)){if(G(e)){let n=e;return e.update&&(n.update=await t.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),n}return await t.validateInput(e)}if(t===md&&Z.isInstance(n)){if(G(e)){let t=e;return e.update&&(t.update=await n.validateInput(Array.isArray(e.update)?Object.fromEntries(e.update):e.update)),t}return await n.validateInput(e)}let r=(()=>{let e=e=>{if(e!=null)return this._metaRegistry.getExtendedChannelSchemas(e,{withReducerSchema:!0})};if(_(t))return e(t);if(t===md)return _(n)?b(e(n)):void 0})();if(G(e)){let t=e;return e.update&&r!=null&&(t.update=Re(r,e.update)),t}return r==null?e:Re(r,e)}isInterrupted(e){return $s(e)}async _validateContext(e){let t=this.builder._configRuntimeSchema;return _(t)&&Re(t,e),e}};function vd(e){return typeof e==`object`&&!!e&&e.channels!==void 0}function yd(e){if(U(e))return[e];let t=[];G(e)?t.push(e):Array.isArray(e)&&t.push(...e.filter(G));let n=[];for(let e of t){if(e.graph===W.PARENT)throw new Gn(e);U(e.goto)||typeof e.goto==`string`?n.push(e.goto):Array.isArray(e.goto)&&n.push(...e.goto)}return n}function bd(){return new Hu({path:new $c({func:yd,tags:[V],trace:!1,recurse:!1,name:`<control_branch>`})})}var xd=function(e,t){let{name:n,checkpointer:r,store:i,cache:a}=typeof e==`string`?{name:e,checkpointer:void 0,store:void 0}:e;if(il(t)||al(t))throw Error(`Generators are disallowed as entrypoints. For streaming responses, use config.write.`);let o=Pl(n,t);function s(e){return typeof e==`object`&&!!e&&`__lg_type`in e&&e.__lg_type===`__pregel_final`}let c=new $c({name:`pluckReturnValue`,func:e=>s(e)?e.value:e}),l=new $c({name:`pluckSaveValue`,func:e=>s(e)?e.save:e}),u=new ml({bound:o,triggers:[R],channels:[R],writers:[new Y([{channel:z,value:sl,mapper:c},{channel:Us,value:sl,mapper:l}],[V])]});return new Bu({name:n,checkpointer:r,nodes:{[n]:u},channels:{[R]:new Vu,[z]:new hs,[Us]:new hs},inputChannels:R,outputChannels:z,streamChannels:z,streamMode:`updates`,store:i,cache:a})};xd.final=function({value:e,save:t}){return{value:e,save:t,__lg_type:`__pregel_final`}},vs.Root({messages:vs({reducer:sd,default:()=>[]})});var Sd={reducer:{fn:sd},jsonSchemaExtra:{langgraph_type:`messages`},default:()=>[]};T({messages:ud(h(),Sd)}),Rn();var Cd=class extends Error{constructor(){super(`The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.`)}},wd=class extends Error{toolNames;constructor(e){super(`The model has called multiple tools: ${e.join(`, `)} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=e}},Td=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(e=>`\n - ${e}`).join(``)}.`),this.toolName=e,this.errors=t}},Ed=class extends Error{toolCall;toolError;constructor(e,t){let n=e instanceof Error?e:Error(String(e)),r=JSON.stringify(t.args);super(`Error invoking tool '${t.name}' with kwargs ${r} with error: ${n.stack}\n Please fix the error and try again.`),this.toolCall=t,this.toolError=n}},Dd=class e extends Error{static"~brand"=`MiddlewareError`;constructor(e,t){let n=e instanceof Error?e.message:String(e);super(n),this.name=e instanceof Error?e.name:`${t[0].toUpperCase()+t.slice(1)}Error`,e instanceof Error&&(this.cause=e)}static wrap(t,n){return qn(t)?t:new e(t,n)}static isInstance(e){return e instanceof Error&&`~brand`in e&&e[`~brand`]===`MiddlewareError`}};function Od(e){return`invoke`in e&&typeof e.invoke==`function`&&`_streamResponseChunks`in e}function kd(e){return typeof e==`object`&&!!e&&`_queuedMethodOperations`in e&&`_getModelInstance`in e&&typeof e._getModelInstance==`function`}var Ad=!0,jd=0,Md=class e{constructor(e,t,n){this.schema=e,this.tool=t,this.options=n}get name(){return this.tool.function.name}static fromSchema(t,n){function r(e){return e??`extract-${++jd}`}if(_e(t)){let i=fe(t);return new e(i,{type:`function`,function:{name:r(i.title),strict:!1,description:i.description??`Tool for extracting structured output from the model's response.`,parameters:i}},n)}let i;return i=typeof t.name==`string`&&typeof t.parameters==`object`&&t.parameters!=null?t:{name:r(t.title),description:t.description??``,parameters:t.schema||t},new e(fe(t),{type:`function`,function:i},n)}parse(e){let t=new ft(this.schema).validate(e);if(!t.valid)throw new Td(this.name,t.errors.map(e=>e.error));return e}},Nd=class e{_schemaType;schema;strict;constructor(e,t){if(`schema`in e&&typeof e.schema==`object`&&e.schema!==null&&!(`type`in e)){let t=e;this.schema=t.schema,this.strict=t.strict??Ad}else this.schema=e,this.strict=t??Ad}static fromSchema(t,n){return new e(fe(t),n)}parse(e){let t;if(typeof e.content==`string`)t=e.content;else if(Array.isArray(e.content)){for(let n of e.content)if(typeof n==`object`&&n&&`type`in n&&n.type===`text`&&`text`in n&&typeof n.text==`string`){t=n.text;break}}if(!(!t||t===``))try{let e=JSON.parse(t);return new ft(this.schema).validate(e).valid?e:void 0}catch{}}};function Pd(e,t,n){if(!e||typeof e==`object`&&e&&`__responseFormatUndefined`in e)return[];if(Array.isArray(e)){if(e.every(e=>e instanceof Md||e instanceof Nd))return e;if(e.every(e=>_(e))||e.every(e=>typeof e==`object`&&!!e&&!_(e)))return e.map(e=>Md.fromSchema(e,t));throw Error(`Invalid response format: list contains mixed types.
|
|
29
|
-
All items must be either InteropZodObject or plain JSON schema objects.`)}if(e instanceof Md||e instanceof Nd)return[e];let r=zd(n);if(_(e)||typeof e==`object`&&e&&`properties`in e)return r?[Nd.fromSchema(e)]:[Md.fromSchema(e,t)];throw Error(`Invalid response format: ${String(e)}`)}function Fd(e,t){return Pd(e,t)}function Id(e){if(typeof e==`object`&&e&&`schema`in e&&!_e(e)&&!(`type`in e)){let{schema:t,strict:n}=e;return Nd.fromSchema(t,n)}return Nd.fromSchema(e)}var Ld=[`ChatOpenAI`,`ChatXAI`],Rd=[`grok`,`gpt-5`,`gpt-4.1`,`gpt-4o`,`gpt-oss`,`o3-pro`,`o3-mini`];function zd(e){if(!e)return!1;if(typeof e==`string`){let t=e.split(`:`).pop();return Rd.some(e=>t.includes(e))}if(kd(e))return zd(e._defaultConfig.model);if(!Od(e))return!1;let t=e.getName();return!!(t===`FakeToolCallingChatModel`||Ld.includes(t)&&(`model`in e&&Rd.some(t=>typeof e.model==`string`&&e.model.includes(t))||t===`FakeToolCallingModel`&&`structuredResponse`in e))}function Bd(e){let t=0;for(let n of e){let e;e=typeof n.content==`string`?n.content:Array.isArray(n.content)?n.content.map(e=>typeof e==`string`?e:e.type===`text`&&`text`in e?e.text:``).join(``):``,w.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(e+=JSON.stringify(n.tool_calls)),A.isInstance(n)&&(e+=n.tool_call_id??``),t+=e.length}return Math.ceil(t/4)}function Vd(e){if(!(!e||typeof e==`function`))return e.canJumpTo}function Hd(e){return typeof e==`function`?e:e.hook}function Ud(e){return new Promise(t=>setTimeout(t,e))}function Wd(e,t){let{backoffFactor:n,initialDelayMs:r,maxDelayMs:i,jitter:a}=e,o;if(o=n===0?r:r*n**t,o=Math.min(o,i),a&&o>0){let e=o*.25;o+=(Math.random()*2-1)*e,o=Math.max(0,o)}return o}var Gd=Symbol(`AgentMiddleware`);function Q(e){return{[Gd]:!0,name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools}}var Kd=class e extends Xt{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:t=`openai`,index:n=0,structuredResponse:r,indexRef:i,...a}={}){super(a),this.toolCalls=e,this.toolStyle=t,this.indexRef=i??{current:n},this.structuredResponse=r}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return`fake-tool-calling`}_combineLLMOutput(){return[]}bindTools(t){let n=new e({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...t],n}withStructuredOutput(e){return new We({func:async()=>this.structuredResponse})}async _generate(e,t,n){let r=e[e.length-1].content;e.length>1&&(r=e.map(e=>e.content).filter(Boolean).map(e=>typeof e==`string`?e:typeof e==`object`&&`text`in e?e.text:Array.isArray(e)?e.map(e=>typeof e==`string`?e:typeof e==`object`&&`text`in e?e.text:``).join(`-`):JSON.stringify(e)).join(`-`)),(e.length===1||e.length===2&&e.every(O.isInstance))&&this.index!==0&&(this.index=0);let i=this.toolCalls[this.index]||[],a=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);let o=new w({content:r,id:a,tool_calls:i.length>0?i.map(e=>({...e,type:`tool_call`})):void 0});return{generations:[{text:r,message:o}],llmOutput:{}}}},qd=Symbol.for(`langgraph-zod`);qd in globalThis||(globalThis[qd]=new WeakSet);function Jd(e){let t=globalThis[qd];t.has(e)||(Object.defineProperty(e,`langgraph`,{get(){let e=this;return{metadata(t){return ud(e,{jsonSchemaExtra:t})},reducer(t,n){return ud(e,{default:ae(e),reducer:{schema:n,fn:t}})}}}}),t.add(e))}try{Jd(ye.prototype),Jd(At.prototype)}catch(e){throw Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}new class extends St{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let n=t[0];if(n&&!n?.default){let t=ae(e);t!=null&&(n.default=t)}return super.add(e,...t)}}(ld);function Yd(e=!0,t,n=[]){let r={jumpTo:new td},i={},a={},o=e=>{if(Z.isInstance(e)){for(let[t,n]of Object.entries(e.fields))t.startsWith(`_`)||t in r||(r[t]=n,$u.isInstance(n)?(i[t]=n.inputSchema||n.valueSchema,a[t]=n.valueSchema):(i[t]=n,a[t]=n));return}let t=Ve(e);for(let[e,n]of Object.entries(t))if(!e.startsWith(`_`)&&!(e in r)){if(ct(n)){let t=ld.get(n);if(t?.reducer){t.reducer.schema?(r[e]=new $u(n,{inputSchema:t.reducer.schema,reducer:t.reducer.fn}),i[e]=t.reducer.schema,a[e]=n):(r[e]=new $u(n,{reducer:t.reducer.fn}),i[e]=n,a[e]=n);continue}}r[e]=n,i[e]=n,a[e]=n}};t&&(Z.isInstance(t)||_(t))&&o(t);for(let e of n)e.stateSchema&&(Z.isInstance(e.stateSchema)||_(e.stateSchema))&&o(e.stateSchema);return e&&(a.structuredResponse=new td),{state:new Z({messages:cd,...r}),input:new Z({messages:cd,...i}),output:new Z({messages:cd,...a})}}var Xd=/<name>(.*?)<\/name>/s,Zd=/<content>(.*?)<\/content>/s;function Qd(e,t){if(Z.isInstance(e)){let n={};for(let r of Object.keys(e.fields))r in t&&(n[r]=t[r]);return n}if(_e(e))return Re(e,t);throw Error(`Invalid state schema type: ${typeof e}`)}function $d(e){if(!w.isInstance(e)||we.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new w({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new w({...e.lc_kwargs,content:n,name:void 0})}function ef(e){if(!w.isInstance(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(Xd),r=e.text.match(Zd);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(Xd),r=e.text.match(Zd);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(Xd),a=r.match(Zd);if(!i||!a)return e;n=i[1],t=a[1]}return new w({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function tf(e){return E.isRunnable(e)}function nf(e){return Od(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}var rf=(e,t,n={})=>{if(nf(e))return e.bindTools(t,n);if(
|
|
30
|
-
`);throw Error(`Middleware "${r.name}" has required state fields that must be initialized:\n${a}\n\nTo fix this, either:\n1. Provide default values in your middleware's state schema using .default():\n stateSchema: z.object({\n myField: z.string().default("default value")\n })\n\n2. Or make the fields optional using .optional():\n stateSchema: z.object({\n myField: z.string().optional()\n })\n\n3. Or ensure you pass these values when invoking the agent:\n agent.invoke({\n messages: [...],\n ${i.error.issues[0]?.path.join(`.`)}: "value"\n })`)}return n}function ff(e){let t={messages:kt(()=>[]),structuredResponse:Ot().optional()};if(!e)return M(t);let n;if(Z.isInstance(e)){n={};for(let[t,r]of Object.entries(e.fields))$u.isInstance(r)?n[t]=r.inputSchema||r.valueSchema:n[t]=r}else n=e.shape;let r={...t};for(let[e,t]of Object.entries(n))e.startsWith(`_`)?r[e]=t.optional():r[e]=t;return M(r)}function pf(e){if(_(e))return b(e);if(Z.isInstance(e)){let t={};for(let[n,r]of Object.entries(e.fields)){let e;e=$u.isInstance(r)?r.inputSchema||r.valueSchema:r,t[n]=ct(e)?e.optional():Ot().optional()}return M(t)}return M({})}function mf(e){if(e){if([`model_request`,`tools`,`__end__`].includes(e))return e;if(e===`model`)return`model_request`;if(e===`tools`)return`tools`;if(e===`end`)return z;throw Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function hf(...e){return AbortSignal.any(e.filter(e=>typeof e==`object`&&!!e&&`aborted`in e&&typeof e.aborted==`boolean`))}var gf=class extends E{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){let n=bt(this.config,t),r=await c.runWithConfig(n,async()=>this.func(e,n));return E.isRunnable(r)&&this.recurse?await c.runWithConfig(n,async()=>r.invoke(e,n)):(this.#e=r,r)}};function _f(e,t){let n,r;if(t===`inline`)n=$d,r=ef;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return qe.from([We.from(i),e,We.from(r)])}function vf(e){return w.isInstance(e)||typeof e==`object`&&!!e&&`structuredResponse`in e&&`messages`in e}var $=`model_request`,yf=class extends gf{#e;#t;#n;constructor(e){super({name:e.name??`model`,func:(e,t)=>this.#i(e,t)}),this.#e=e,this.#t=e.systemMessage}#r(e){if(!this.#e.responseFormat)return;let t=Pd(this.#e.responseFormat,void 0,e);return t.every(e=>e instanceof Nd)?{type:`native`,strategy:t[0]}:{type:`tool`,tools:t.filter(e=>e instanceof Md).reduce((e,t)=>(e[t.name]=t,e),{})}}async#i(e,t){let n=e.messages.at(-1);if(n&&A.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};let r=await this.#o(e,t);return`structuredResponse`in r?{messages:[...e.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof W?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#u(e,r)?{messages:[new w({content:`Sorry, need more steps to process this request.`,name:this.name,id:r.id})]}:{messages:[r]})}#a(){if(typeof this.#e.model==`string`)return In(this.#e.model);if(this.#e.model)return this.#e.model;throw Error("No model option was provided, either via `model` option.")}async#o(e,t,n={}){let r=await this.#a(),i=t,a=async e=>{af(e.model);let r=this.#r(e.model),i=await this.#d(e.model,e,r),a=[...this.#n.text===``?[]:[this.#n],...e.messages],o=hf(this.#e.signal,t.signal),s=await Fe(i.invoke(a,{...t,signal:o}),o);if(r?.type===`native`){let e=r.strategy.parse(s);return e?{structuredResponse:e,messages:[s]}:s}if(!r||!s.tool_calls)return s;let c=s.tool_calls.filter(e=>e.name in r.tools);if(c.length===0)return s;if(c.length>1)return this.#s(s,c,r);let l=r.tools[c[0].name]?.options?.toolMessageContent;return this.#c(s,c[0],r,l??n.lastMessage)},o=this.#e.wrapModelCallHookMiddleware??[],s=a;for(let t=o.length-1;t>=0;t--){let[n,r]=o[t];if(n.wrapModelCall){let t=s,a=n,o=r;s=async r=>{let s=a.contextSchema?Re(a.contextSchema,i?.context||{}):i?.context,c=Object.freeze({context:s,writer:i.writer,interrupt:i.interrupt,signal:i.signal}),l={...r,state:{...n.stateSchema?Re(pf(n.stateSchema),e):{},...o(),messages:e.messages},runtime:c},u=async e=>{let n=e.tools??[],r=n.filter(e=>tf(e)&&!this.#e.toolClasses.some(t=>t.name===e.name));if(r.length>0)throw Error(`You have added a new tool in "wrapModelCall" hook of middleware "${a.name}": ${r.map(e=>e.name).join(`, `)}. This is not supported.`);let i=n.filter(e=>tf(e)&&this.#e.toolClasses.every(t=>t!==e));if(i.length>0)throw Error(`You have modified a tool in "wrapModelCall" hook of middleware "${a.name}": ${i.map(e=>e.name).join(`, `)}. This is not supported.`);let o=e,s=e.systemPrompt!==this.#n.text,c=e.systemMessage!==this.#n;if(s&&c)throw Error(`Cannot change both systemPrompt and systemMessage in the same request.`);return s&&(this.#n=new D({content:[{type:`text`,text:e.systemPrompt}]}),o={...e,systemPrompt:this.#n.text,systemMessage:this.#n}),c&&(this.#n=new D({...e.systemMessage}),o={...e,systemPrompt:this.#n.text,systemMessage:this.#n}),t(o)};if(!a.wrapModelCall)return u(l);try{let e=await a.wrapModelCall(l,u);if(!vf(e))throw Error(`Invalid response from "wrapModelCall" in middleware "${a.name}": expected AIMessage, got ${typeof e}`);return e}catch(e){throw Dd.wrap(e,a.name)}}}}this.#n=this.#t;let c={model:r,systemPrompt:this.#n?.text,systemMessage:this.#n,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:i?.context,writer:i.writer,interrupt:i.interrupt,signal:i.signal})};return s(c)}#s(e,t,n){let r=new wd(t.map(e=>e.name));return this.#l(r,e,t[0],n)}#c(e,t,n,r){let i=n.tools[t.name];try{let n=i.parse(t.args);return{structuredResponse:n,messages:[e,new A({tool_call_id:t.id??``,content:JSON.stringify(n),name:t.name}),new w(r??`Returning structured response: ${JSON.stringify(n)}`)]}}catch(r){return this.#l(r,e,t,n)}}async#l(e,t,n,r){let i=Object.values(r.tools).at(0)?.options?.handleError,a=n.id;if(!a)throw Error(`Tool call ID is required to handle tool output errors. Please provide a tool call ID.`);if(i===!1)throw e;if(i===void 0||typeof i==`boolean`&&i||Array.isArray(i)&&i.some(e=>e instanceof wd))return new W({update:{messages:[t,new A({content:e.message,tool_call_id:a})]},goto:$});if(typeof i==`string`)return new W({update:{messages:[t,new A({content:i,tool_call_id:a})]},goto:$});if(typeof i==`function`){let n=await i(e);if(typeof n!=`string`)throw Error(`Error handler must return a string.`);return new W({update:{messages:[t,new A({content:n,tool_call_id:a})]},goto:$})}return new W({update:{messages:[t,new A({content:e.message,tool_call_id:a})]},goto:$})}#u(e,t){let n=w.isInstance(t)&&t.tool_calls?.every(e=>this.#e.shouldReturnDirect.has(e.name)),r=`remainingSteps`in e?e.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&of(e.messages.at(-1))))}async#d(e,t,n){let i={},a=Object.values(n&&`tools`in n?n.tools:{}),o=[...t?.tools??this.#e.toolClasses,...a.map(e=>e.tool)],s=t?.toolChoice||(a.length>0?`any`:void 0);if(n?.type===`native`){let e=t?.modelSettings?.strict??n?.strategy?.strict??!0,a={name:n.strategy.schema?.name??`extract`,description:r(n.strategy.schema),schema:n.strategy.schema,strict:e};Object.assign(i,{response_format:{type:`json_schema`,json_schema:a},output_format:{type:`json_schema`,schema:n.strategy.schema},headers:{"anthropic-beta":`structured-outputs-2025-11-13`},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:n.strategy.schema},strict:e})}let c=await cf(e,o,{...i,...t?.modelSettings,tool_choice:s});return this.#e.includeAgentName===`inline`?_f(c,this.#e.includeAgentName):c}getState(){let e=super.getState();return{messages:[],...e&&!(e instanceof W)?e:{}}}},bf=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(`, `)}].`,xf=`tools`,Sf=e=>Array.isArray(e)&&e.every(gt.isInstance),Cf=e=>typeof e==`object`&&!!e&&`messages`in e&&Sf(e.messages),wf=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e;function Tf(e,t){return e instanceof Ed?new A({content:e.message,tool_call_id:t.id,name:t.name}):new A({content:`${e}\n Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var Ef=class extends gf{tools;trace=!1;signal;handleToolErrors=Tf;wrapToolCall;constructor(e,t){let{name:n,tags:r,handleToolErrors:i,signal:a,wrapToolCall:o}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.options=t,this.tools=e,this.handleToolErrors=i??this.handleToolErrors,this.signal=a,this.wrapToolCall=o}#e(e,t,n){if(Jn(e)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors==`function`){let n=this.handleToolErrors(e,t);if(n&&A.isInstance(n))return n;throw e}else if(this.handleToolErrors)return new A({name:t.name,content:`${e}\n Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,n){let r=t,i={context:r?.context,writer:r?.writer,interrupt:r?.interrupt,signal:r?.signal},a=this.tools.find(t=>t.name===e.name),o=async e=>{let{toolCall:n,tool:r}=e,i=r??this.tools.find(e=>e.name===n.name);if(i===void 0){let e=this.tools.map(e=>e.name);return new A({content:bf(n.name,e),tool_call_id:n.id,name:n.name,status:`error`})}let a=i;try{let e=await a.invoke({...n,type:`tool_call`},{...t,config:t,toolCallId:n.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:hf(this.signal,t.signal)});return A.isInstance(e)||G(e)?e:new A({name:a.name,content:typeof e==`string`?e:JSON.stringify(e),tool_call_id:n.id})}catch(e){throw e instanceof Ze?new Ed(e,n):e}},s={toolCall:e,tool:a,state:n,runtime:i};if(this.wrapToolCall)try{return await this.wrapToolCall(s,o)}catch(t){return this.#e(t,e,!0)}if(!a){let t=this.tools.map(e=>e.name);return new A({content:bf(e.name,t),tool_call_id:e.id,name:e.name,status:`error`})}try{return await o(s)}catch(t){return this.#e(t,e,!1)}}async run(e,t){let n;if(wf(e)){let{lg_tool_call:r,jumpTo:i,...a}=e;n=[await this.runTool(e.lg_tool_call,t,a)]}else{let r;if(Sf(e))r=e;else if(Cf(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(w.isInstance(t)){a=t;break}}if(!w.isInstance(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(n=>this.runTool(n,t,e))??[])}if(!n.some(G))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)G(t)?t.graph===W.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>Df(e))?i?i.goto.push(...t.goto):i=new W({graph:W.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}};function Df(e){return e instanceof H}var Of=class{},kf=class{},Af=class extends gf{#e;constructor(e,t){super(e),this.#e=t}async invokeMiddleware(e,t){let n={};if(this.middleware.contextSchema){let e=this.middleware.contextSchema?.shape;if(e){let r={},i=t?.context||{};for(let t of Object.keys(e))t in i&&(r[t]=i[t]);n=Re(this.middleware.contextSchema,r)}}let r={...this.#e.getState(),...e,messages:e.messages},i={context:n,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},a=await this.runHook(r,Object.freeze(Object.assign(new kf,{...i,context:Object.freeze(Object.assign(new Of,n))})));if(!a)return{...r,jumpTo:void 0};let o,s;if(this.name?.startsWith(`BeforeAgentNode_`)?(o=Vd(this.middleware.beforeAgent),s=`beforeAgent.canJumpTo`):this.name?.startsWith(`BeforeModelNode_`)?(o=Vd(this.middleware.beforeModel),s=`beforeModel.canJumpTo`):this.name?.startsWith(`AfterAgentNode_`)?(o=Vd(this.middleware.afterAgent),s=`afterAgent.canJumpTo`):this.name?.startsWith(`AfterModelNode_`)&&(o=Vd(this.middleware.afterModel),s=`afterModel.canJumpTo`),typeof a.jumpTo==`string`&&!o?.includes(a.jumpTo)){let e=o&&o.length>0?`must be one of: ${o?.join(`, `)}.`:s?`no ${s} defined in middleware ${this.middleware.name}`:``;throw Error(`Invalid jump target: ${a.jumpTo}, ${e}.`)}if(typeof a==`object`&&`type`in a){if(a.type===`terminate`){if(a.error)throw a.error;return{...r,...a.result||{},jumpTo:a.jumpTo}}throw Error(`Invalid control action: ${JSON.stringify(a)}`)}return{...r,...a,jumpTo:a.jumpTo}}get nodeOptions(){return{input:ff(this.middleware.stateSchema)}}},jf=class extends Af{lc_namespace=[`langchain`,`agents`,`beforeAgentNodes`];constructor(e,t){super({name:`BeforeAgentNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.beforeAgent)(e,t)}},Mf=class extends Af{lc_namespace=[`langchain`,`agents`,`beforeModelNodes`];constructor(e,t){super({name:`BeforeModelNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.beforeModel)(e,t)}},Nf=class extends Af{lc_namespace=[`langchain`,`agents`,`afterModelNodes`];constructor(e,t){super({name:`AfterModelNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.afterModel)(e,t)}},Pf=class extends Af{lc_namespace=[`langchain`,`agents`,`afterAgentNodes`];constructor(e,t){super({name:`AfterAgentNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.afterAgent)(e,t)}},Ff=class{#e=new Map;addNode(e,t){this.#e.set(e.name,[...this.#e.get(e.name)??[],t])}getState(e){let t=(this.#e.get(e)??[]).reduce((e,t)=>({...e,...t.getState()??{}}),{});return delete t.jumpTo,t}},If=class{#e;#t=`v2`;#n;#r=new Ff;constructor(e){if(this.options=e,this.#t=e.version??this.#t,!e.model)throw Error("`model` option is required to create an agent.");typeof e.model!=`string`&&af(e.model);let t=this.options.middleware?.filter(e=>e.tools).flatMap(e=>e.tools)??[],n=[...e.tools??[],...t],r=new Set(n.filter(tf).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name)),{state:i,input:a,output:o}=Yd(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),s=new hd(i,{input:a,output:o,context:this.options.contextSchema}),c=[],l=[],u=[],d=[],f=[];this.#n=new yf({model:this.options.model,systemMessage:sf(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:f});let p=new Set,m=this.options.middleware??[];for(let e=0;e<m.length;e++){let t,n,r,i,a=m[e];if(p.has(a.name))throw Error(`Middleware ${a.name} is defined multiple times`);if(p.add(a.name),a.beforeAgent){t=new jf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,t);let n=`${a.name}.before_agent`;c.push({index:e,name:n,allowed:Vd(a.beforeAgent)}),s.addNode(n,t,t.nodeOptions)}if(a.beforeModel){n=new Mf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,n);let t=`${a.name}.before_model`;l.push({index:e,name:t,allowed:Vd(a.beforeModel)}),s.addNode(t,n,n.nodeOptions)}if(a.afterModel){r=new Nf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,r);let t=`${a.name}.after_model`;u.push({index:e,name:t,allowed:Vd(a.afterModel)}),s.addNode(t,r,r.nodeOptions)}if(a.afterAgent){i=new Pf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,i);let t=`${a.name}.after_agent`;d.push({index:e,name:t,allowed:Vd(a.afterAgent)}),s.addNode(t,i,i.nodeOptions)}a.wrapModelCall&&f.push([a,()=>this.#r.getState(a.name)])}s.addNode($,this.#n);let h=m.some(e=>e.wrapToolCall),g=n.filter(tf);if(g.length>0||h){let e=new Ef(g,{signal:this.options.signal,wrapToolCall:uf(m)});s.addNode(xf,e)}let _;_=c.length>0?c[0].name:l.length>0?l[0].name:$;let v=l.length>0?l[0].name:$,y=d.length>0?d[d.length-1].name:z;s.addEdge(R,_);let b=g.length>0||h;for(let e=0;e<c.length;e++){let t=c[e],n=t.name,r=e===c.length-1?v:c[e+1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e.map(e=>e===`__end__`?y:e)]));s.addConditionalEdges(n,this.#l(g,r,y,b),i)}else s.addEdge(n,r)}for(let e=0;e<l.length;e++){let t=l[e],n=t.name,r=e===l.length-1?$:l[e+1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e]));s.addConditionalEdges(n,this.#u(g,r,b),i)}else s.addEdge(n,r)}let x=u.at(-1);if(u.length>0&&x)s.addEdge($,x.name);else{let e=this.#i(g,!1,b).map(e=>e===`__end__`?y:e);e.length===1?s.addEdge($,e[0]):s.addConditionalEdges($,this.#o(y),e)}for(let e=u.length-1;e>0;e--){let t=u[e],n=t.name,r=u[e-1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e]));s.addConditionalEdges(n,this.#c(g,t.allowed,r,b),i)}else s.addEdge(n,r)}if(u.length>0){let e=u[0],t=e.name,n=this.#i(g,!0,b).filter(e=>e!==`tools`||b),r=!!(e.allowed&&e.allowed.length>0),i=n.map(e=>e===`__end__`?y:e);s.addConditionalEdges(t,this.#s(g,r,y,b),i)}for(let e=d.length-1;e>0;e--){let t=d[e],n=t.name,r=d[e-1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e]));s.addConditionalEdges(n,this.#c(g,t.allowed,r,b),i)}else s.addEdge(n,r)}if(d.length>0){let e=d[0],t=e.name;if(e.allowed&&e.allowed.length>0){let n=e.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),r=Array.from(new Set([z,...n]));s.addConditionalEdges(t,this.#c(g,e.allowed,z,b),r)}else s.addEdge(t,z)}if(b){let e=v;r.size>0?s.addConditionalEdges(xf,this.#a(r,y),[e,y]):s.addEdge(xf,e)}this.#e=s.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#i(e,t=!1,n=e.length>0){let r=[];return n&&r.push(xf),t&&r.push($),r.push(z),r}#a(e,t){return n=>{let r=n.messages,i=r[r.length-1];return A.isInstance(i)&&i.name&&e.has(i.name)?this.options.responseFormat?$:t:$}}#o(e=z){return t=>{let n=t.messages.at(-1);if(!w.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(e=>e.name.startsWith(`extract-`)))return e;if(this.#t===`v1`)return xf;let r=n.tool_calls.filter(e=>!e.name.startsWith(`extract-`));return r.length===0?e:r.map(e=>new H(xf,{...t,lg_tool_call:e}))}}#s(e,t,n,r=e.length>0){let i=!!this.options.responseFormat;return e=>{let a=e,o=a.messages,s=o.at(-1);if(w.isInstance(s)&&(!s.tool_calls||s.tool_calls.length===0))return n;if(t&&a.jumpTo){let t=mf(a.jumpTo);return t===`__end__`?n:t===`tools`?r?new H(xf,{...e,jumpTo:void 0}):n:new H($,{...e,jumpTo:void 0})}let c=o.filter(A.isInstance),l=o.filter(w.isInstance).at(-1),u=l?.tool_calls?.filter(e=>!c.some(t=>t.tool_call_id===e.id));if(u&&u.length>0)return u.map(t=>new H(xf,{...e,lg_tool_call:t}));let d=l?.tool_calls?.some(e=>e.name.startsWith(`extract-`));if(u&&u.length===0&&!d&&i)return $;if(!w.isInstance(s)||!s.tool_calls||s.tool_calls.length===0)return n;let f=s.tool_calls.every(e=>e.name.startsWith(`extract-`)),p=s.tool_calls.some(e=>!e.name.startsWith(`extract-`));return f||!p?n:xf}}#c(e,t,n,r=e.length>0){let i=new Set(t.map(e=>mf(e)));return e=>{let t=e;if(t.jumpTo){let n=mf(t.jumpTo);if(n===`__end__`&&i.has(`__end__`))return z;if(n===`tools`&&i.has(`tools`))return r?new H(xf,{...e,jumpTo:void 0}):z;if(n===`model_request`&&i.has(`model_request`))return new H($,{...e,jumpTo:void 0})}return n}}#l(e,t,n,r=e.length>0){return e=>{let i=e;if(!i.jumpTo)return t;let a=mf(i.jumpTo);return a===`__end__`?n:a===`tools`?r?new H(xf,{...e,jumpTo:void 0}):n:new H($,{...e,jumpTo:void 0})}}#u(e,t,n=e.length>0){return e=>{let r=e;if(!r.jumpTo)return t;let i=mf(r.jumpTo);return i===`__end__`?z:i===`tools`?n?new H(xf,{...e,jumpTo:void 0}):z:new H($,{...e,jumpTo:void 0})}}async#d(e,t){if(!this.options.middleware||this.options.middleware.length===0||e instanceof W||!e)return e;let n=await df(this.options.middleware,e),r={...(await this.#e.getState(t).catch(()=>({values:{}}))).values,...e};if(!r)return r;for(let[e,t]of Object.entries(n))e in r||(r[e]=t);return r}async invoke(e,t){let n=await this.#d(e,t);return this.#e.invoke(n,t)}async stream(e,t){let n=await this.#d(e,t);return this.#e.stream(n,t)}async drawMermaidPng(e){let t=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(t)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,t,n){return this.#e.streamEvents(e,{...t,version:t?.version??`v2`},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,t){return this.#e.getState(e,t)}getStateHistory(e,t){return this.#e.getStateHistory(e,t)}getSubgraphs(e,t){return this.#e.getSubgraphs(e,t)}getSubgraphAsync(e,t){return this.#e.getSubgraphsAsync(e,t)}updateState(e,t,n){return this.#e.updateState(e,t,n)}get builder(){return this.#e.builder}};function Lf(e){return new If(e)}var Rf=$e().args(h(),h(),h()).returns(st([k(),ue(k())])),zf=[`approve`,`edit`,`reject`],Bf=T({allowedDecisions:ve(ee(zf)),description:st([k(),Rf]).optional(),argsSchema:n(v()).optional()}),Vf=T({interruptOn:n(st([xe(),Bf])).optional(),descriptionPrefix:k().default(`Tool execution requires approval`)});function Hf(e){let t=async(t,n,r,i)=>{let a=t.name,o=t.args,s=n.description,c;c=typeof s==`function`?await s(t,r,i):s===void 0?`${e.descriptionPrefix??`Tool execution requires approval`}\n\nTool: ${a}\nArgs: ${JSON.stringify(o,null,2)}`:s;let l={name:a,args:o,description:c},u={actionName:a,allowedDecisions:n.allowedDecisions};return n.argsSchema&&(u.argsSchema=n.argsSchema),{actionRequest:l,reviewConfig:u}},n=(e,t,n)=>{let r=n.allowedDecisions;if(e.type===`approve`&&r.includes(`approve`))return{revisedToolCall:t,toolMessage:null};if(e.type===`edit`&&r.includes(`edit`)){let n=e.editedAction;if(!n||typeof n.name!=`string`)throw Error(`Invalid edited action for tool "${t.name}": name must be a string`);if(!n.args||typeof n.args!=`object`)throw Error(`Invalid edited action for tool "${t.name}": args must be an object`);return{revisedToolCall:{type:`tool_call`,name:n.name,args:n.args,id:t.id},toolMessage:null}}if(e.type===`reject`&&r.includes(`reject`)){if(e.message!==void 0&&typeof e.message!=`string`)throw Error(`Tool call response for "${t.name}" must be a string, got ${typeof e.message}`);return{revisedToolCall:t,toolMessage:new A({content:e.message??`User rejected the tool call for \`${t.name}\` with id ${t.id}`,name:t.name,tool_call_id:t.id,status:`error`})}}let i=`Unexpected human decision: ${JSON.stringify(e)}. Decision type '${e.type}' is not allowed for tool '${t.name}'. Expected one of ${JSON.stringify(r)} based on the tool's configuration.`;throw Error(i)};return Q({name:`HumanInTheLoopMiddleware`,contextSchema:Vf,afterModel:{canJumpTo:[`model`],hook:async(r,i)=>{let a=Re(Vf,{...e,...i.context||{}});if(!a)return;let{messages:o}=r;if(!o.length)return;let s=[...o].reverse().find(e=>w.isInstance(e));if(!s||!s.tool_calls?.length||!a.interruptOn)return;let c={};for(let[e,t]of Object.entries(a.interruptOn))typeof t==`boolean`?t===!0&&(c[e]={allowedDecisions:[...zf]}):t.allowedDecisions&&(c[e]=t);let l=[],u=[];for(let e of s.tool_calls)e.name in c?l.push(e):u.push(e);if(!l.length)return;let d=[],f=[];for(let e of l){let n=c[e.name],{actionRequest:a,reviewConfig:o}=await t(e,n,r,i);d.push(a),f.push(o)}let p=(await Qc({actionRequests:d,reviewConfigs:f})).decisions;if(!p||!Array.isArray(p))throw Error(`Invalid HITLResponse: decisions must be a non-empty array`);if(p.length!==l.length)throw Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${l.length}).`);let m=[...u],h=[],g=p.some(e=>e.type===`reject`);for(let e=0;e<p.length;e++){let t=p[e],r=l[e],i=c[r.name],{revisedToolCall:a,toolMessage:o}=n(t,r,i);a&&(!g||t.type===`reject`)&&m.push(a),o&&h.push(o)}w.isInstance(s)&&(s.tool_calls=m);let _=g?`model`:void 0;return{messages:[s,...h],jumpTo:_}}}})}var Uf=`<role>
|
|
29
|
+
All items must be either InteropZodObject or plain JSON schema objects.`)}if(e instanceof Md||e instanceof Nd)return[e];let r=zd(n);if(_(e)||typeof e==`object`&&e&&`properties`in e)return r?[Nd.fromSchema(e)]:[Md.fromSchema(e,t)];throw Error(`Invalid response format: ${String(e)}`)}function Fd(e,t){return Pd(e,t)}function Id(e){if(typeof e==`object`&&e&&`schema`in e&&!_e(e)&&!(`type`in e)){let{schema:t,strict:n}=e;return Nd.fromSchema(t,n)}return Nd.fromSchema(e)}var Ld=[`ChatOpenAI`,`ChatXAI`],Rd=[`grok`,`gpt-5`,`gpt-4.1`,`gpt-4o`,`gpt-oss`,`o3-pro`,`o3-mini`];function zd(e){if(!e)return!1;if(typeof e==`string`){let t=e.split(`:`).pop();return Rd.some(e=>t.includes(e))}if(kd(e))return zd(e._defaultConfig.model);if(!Od(e))return!1;let t=e.getName();return!!(t===`FakeToolCallingChatModel`||Ld.includes(t)&&(`model`in e&&Rd.some(t=>typeof e.model==`string`&&e.model.includes(t))||t===`FakeToolCallingModel`&&`structuredResponse`in e))}function Bd(e){let t=0;for(let n of e){let e;e=typeof n.content==`string`?n.content:Array.isArray(n.content)?n.content.map(e=>typeof e==`string`?e:e.type===`text`&&`text`in e?e.text:``).join(``):``,w.isInstance(n)&&Array.isArray(n.tool_calls)&&n.tool_calls.length>0&&(e+=JSON.stringify(n.tool_calls)),A.isInstance(n)&&(e+=n.tool_call_id??``),t+=e.length}return Math.ceil(t/4)}function Vd(e){if(!(!e||typeof e==`function`))return e.canJumpTo}function Hd(e){return typeof e==`function`?e:e.hook}function Ud(e){return new Promise(t=>setTimeout(t,e))}function Wd(e,t){let{backoffFactor:n,initialDelayMs:r,maxDelayMs:i,jitter:a}=e,o;if(o=n===0?r:r*n**t,o=Math.min(o,i),a&&o>0){let e=o*.25;o+=(Math.random()*2-1)*e,o=Math.max(0,o)}return o}var Gd=Symbol(`AgentMiddleware`);function Q(e){return{[Gd]:!0,name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools}}var Kd=class e extends Xt{toolCalls;toolStyle;indexRef;structuredResponse;tools=[];constructor({toolCalls:e=[],toolStyle:t=`openai`,index:n=0,structuredResponse:r,indexRef:i,...a}={}){super(a),this.toolCalls=e,this.toolStyle=t,this.indexRef=i??{current:n},this.structuredResponse=r}get index(){return this.indexRef.current}set index(e){this.indexRef.current=e}_llmType(){return`fake-tool-calling`}_combineLLMOutput(){return[]}bindTools(t){let n=new e({toolCalls:this.toolCalls,toolStyle:this.toolStyle,structuredResponse:this.structuredResponse,indexRef:this.indexRef});return n.tools=[...this.tools,...t],n}withStructuredOutput(e){return new We({func:async()=>this.structuredResponse})}async _generate(e,t,n){let r=e[e.length-1].content;e.length>1&&(r=e.map(e=>e.content).filter(Boolean).map(e=>typeof e==`string`?e:typeof e==`object`&&`text`in e?e.text:Array.isArray(e)?e.map(e=>typeof e==`string`?e:typeof e==`object`&&`text`in e?e.text:``).join(`-`):JSON.stringify(e)).join(`-`)),(e.length===1||e.length===2&&e.every(O.isInstance))&&this.index!==0&&(this.index=0);let i=this.toolCalls[this.index]||[],a=this.index.toString();this.index=(this.index+1)%Math.max(1,this.toolCalls.length);let o=new w({content:r,id:a,tool_calls:i.length>0?i.map(e=>({...e,type:`tool_call`})):void 0});return{generations:[{text:r,message:o}],llmOutput:{}}}},qd=Symbol.for(`langgraph-zod`);qd in globalThis||(globalThis[qd]=new WeakSet);function Jd(e){let t=globalThis[qd];t.has(e)||(Object.defineProperty(e,`langgraph`,{get(){let e=this;return{metadata(t){return ud(e,{jsonSchemaExtra:t})},reducer(t,n){return ud(e,{default:ae(e),reducer:{schema:n,fn:t}})}}}}),t.add(e))}try{Jd(ye.prototype),Jd(At.prototype)}catch(e){throw Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}new class extends St{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let n=t[0];if(n&&!n?.default){let t=ae(e);t!=null&&(n.default=t)}return super.add(e,...t)}}(ld);function Yd(e=!0,t,n=[]){let r={jumpTo:new td},i={},a={},o=e=>{if(Z.isInstance(e)){for(let[t,n]of Object.entries(e.fields))t.startsWith(`_`)||t in r||(r[t]=n,$u.isInstance(n)?(i[t]=n.inputSchema||n.valueSchema,a[t]=n.valueSchema):(i[t]=n,a[t]=n));return}let t=Ve(e);for(let[e,n]of Object.entries(t))if(!e.startsWith(`_`)&&!(e in r)){if(ct(n)){let t=ld.get(n);if(t?.reducer){t.reducer.schema?(r[e]=new $u(n,{inputSchema:t.reducer.schema,reducer:t.reducer.fn}),i[e]=t.reducer.schema,a[e]=n):(r[e]=new $u(n,{reducer:t.reducer.fn}),i[e]=n,a[e]=n);continue}}r[e]=n,i[e]=n,a[e]=n}};t&&(Z.isInstance(t)||_(t))&&o(t);for(let e of n)e.stateSchema&&(Z.isInstance(e.stateSchema)||_(e.stateSchema))&&o(e.stateSchema);return e&&(a.structuredResponse=new td),{state:new Z({messages:cd,...r}),input:new Z({messages:cd,...i}),output:new Z({messages:cd,...a})}}var Xd=/<name>(.*?)<\/name>/s,Zd=/<content>(.*?)<\/content>/s;function Qd(e,t){if(Z.isInstance(e)){let n={};for(let r of Object.keys(e.fields))r in t&&(n[r]=t[r]);return n}if(_e(e))return Re(e,t);throw Error(`Invalid state schema type: ${typeof e}`)}function $d(e){if(!w.isInstance(e)||we.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content==`string`)return new w({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],r=0;for(let i of e.content)typeof i==`string`?(r+=1,n.push(`<name>${t}</name><content>${i}</content>`)):typeof i==`object`&&`type`in i&&i.type===`text`?(r+=1,n.push({...i,text:`<name>${t}</name><content>${i.text}</content>`})):n.push(i);return r||n.unshift({type:`text`,text:`<name>${t}</name><content></content>`}),new w({...e.lc_kwargs,content:n,name:void 0})}function ef(e){if(!w.isInstance(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(Xd),r=e.text.match(Zd);return t&&(!r||r[1]===``)?(n=t[1],!1):!0}return!0}).map(e=>{if(e.type===`text`&&typeof e.text==`string`){let t=e.text.match(Xd),r=e.text.match(Zd);return!t||!r?e:(n=t[1],{...e,text:r[1]})}return e});else{let r=e.content,i=r.match(Xd),a=r.match(Zd);if(!i||!a)return e;n=i[1],t=a[1]}return new w({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function tf(e){return E.isRunnable(e)}function nf(e){return Od(e)?`bindTools`in e&&typeof e.bindTools==`function`:!1}var rf=(e,t,n={})=>{if(nf(e))return e.bindTools(t,n);if(nt.isRunnableBinding(e)&&nf(e.bound)){let r=e.bound.bindTools(t,n);return nt.isRunnableBinding(r)?new nt({bound:r.bound,config:{...e.config,...r.config},kwargs:{...e.kwargs,...r.kwargs},configFactories:r.configFactories??e.configFactories}):new nt({bound:r,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function af(e){if(typeof e==`function`)return;let t=e;if(qe.isRunnableSequence(t)&&(t=t.steps.find(e=>nt.isRunnableBinding(e))||t),!kd(t)){if(nt.isRunnableBinding(t)){let e=t.kwargs!=null&&typeof t.kwargs==`object`&&`tools`in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,n=t.config!=null&&typeof t.config==`object`&&`tools`in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(e||n)throw new Cd}if(`tools`in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new Cd}}function of(e){return!!(w.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function sf(e){if(e==null)return new D(``);if(D.isInstance(e))return e;if(typeof e==`string`)return new D({content:[{type:`text`,text:e}]});throw Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof e}`)}async function cf(e,t,n={}){let r=rf(e,t,n);if(r)return r;if(kd(e)){let r=rf(await e._getModelInstance(),t,n);if(r)return r}if(qe.isRunnableSequence(e)){let r=e.steps.findIndex(e=>nt.isRunnableBinding(e)||Od(e)||kd(e));if(r>=0){let i=rf(e.steps[r],t,n);if(i){let t=e.steps.slice();return t.splice(r,1,i),qe.from(t)}}}throw Error(`llm ${e} must define bindTools method.`)}function lf(e){if(e.length===0)return;if(e.length===1)return e[0];function t(e,t){return async(n,r)=>e(n,async e=>t(e,r))}let n=e[e.length-1];for(let r=e.length-2;r>=0;r--)n=t(e[r],n);return n}function uf(e){let t=e.filter(e=>e.wrapToolCall);if(t.length!==0)return lf(t.map(e=>{let t=e.wrapToolCall;return async(n,r)=>{let i=n.state,a=async e=>{let t={...i,...e.state};return r({...e,state:t})};try{let r=await t({...n,state:{messages:i.messages,...e.stateSchema?Qd(e.stateSchema,{...i}):{}}},a);if(!A.isInstance(r)&&!G(r))throw Error(`Invalid response from "wrapToolCall" in middleware "${e.name}": expected ToolMessage or Command, got ${typeof r}`);return r}catch(t){throw Dd.wrap(t,e.name)}}}))}async function df(e,t){let n={};for(let r of e){if(!r.stateSchema)continue;let e=r.stateSchema;if(Z.isInstance(r.stateSchema)){let t={};for(let[e,n]of Object.entries(r.stateSchema.fields))$u.isInstance(n)?t[e]=n.inputSchema||n.valueSchema:t[e]=n;e=M(t)}let i=await ce(m(e,e=>e.startsWith(`_`)),t);if(i.success){Object.assign(n,i.data);continue}let a=i.error.issues.filter(e=>e.code===`invalid_type`).map(e=>` - ${e.path.join(`.`)}: Required`).join(`
|
|
30
|
+
`);throw Error(`Middleware "${r.name}" has required state fields that must be initialized:\n${a}\n\nTo fix this, either:\n1. Provide default values in your middleware's state schema using .default():\n stateSchema: z.object({\n myField: z.string().default("default value")\n })\n\n2. Or make the fields optional using .optional():\n stateSchema: z.object({\n myField: z.string().optional()\n })\n\n3. Or ensure you pass these values when invoking the agent:\n agent.invoke({\n messages: [...],\n ${i.error.issues[0]?.path.join(`.`)}: "value"\n })`)}return n}function ff(e){let t={messages:kt(()=>[]),structuredResponse:Ot().optional()};if(!e)return M(t);let n;if(Z.isInstance(e)){n={};for(let[t,r]of Object.entries(e.fields))$u.isInstance(r)?n[t]=r.inputSchema||r.valueSchema:n[t]=r}else n=e.shape;let r={...t};for(let[e,t]of Object.entries(n))e.startsWith(`_`)?r[e]=t.optional():r[e]=t;return M(r)}function pf(e){if(_(e))return b(e);if(Z.isInstance(e)){let t={};for(let[n,r]of Object.entries(e.fields)){let e;e=$u.isInstance(r)?r.inputSchema||r.valueSchema:r,t[n]=ct(e)?e.optional():Ot().optional()}return M(t)}return M({})}function mf(e){if(e){if([`model_request`,`tools`,`__end__`].includes(e))return e;if(e===`model`)return`model_request`;if(e===`tools`)return`tools`;if(e===`end`)return z;throw Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function hf(...e){return AbortSignal.any(e.filter(e=>typeof e==`object`&&!!e&&`aborted`in e&&typeof e.aborted==`boolean`))}var gf=class extends E{lc_namespace=[`langgraph`];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){let n=bt(this.config,t),r=await c.runWithConfig(n,async()=>this.func(e,n));return E.isRunnable(r)&&this.recurse?await c.runWithConfig(n,async()=>r.invoke(e,n)):(this.#e=r,r)}};function _f(e,t){let n,r;if(t===`inline`)n=$d,r=ef;else throw Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function i(e){return e.map(n)}return qe.from([We.from(i),e,We.from(r)])}function vf(e){return w.isInstance(e)||typeof e==`object`&&!!e&&`structuredResponse`in e&&`messages`in e}var $=`model_request`,yf=class extends gf{#e;#t;#n;constructor(e){super({name:e.name??`model`,func:(e,t)=>this.#i(e,t)}),this.#e=e,this.#t=e.systemMessage}#r(e){if(!this.#e.responseFormat)return;let t=Pd(this.#e.responseFormat,void 0,e);return t.every(e=>e instanceof Nd)?{type:`native`,strategy:t[0]}:{type:`tool`,tools:t.filter(e=>e instanceof Md).reduce((e,t)=>(e[t.name]=t,e),{})}}async#i(e,t){let n=e.messages.at(-1);if(n&&A.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return{messages:[]};let r=await this.#o(e,t);return`structuredResponse`in r?{messages:[...e.messages,...r.messages||[]],structuredResponse:r.structuredResponse}:r instanceof W?r:(r.name=this.name,r.lc_kwargs.name=this.name,this.#u(e,r)?{messages:[new w({content:`Sorry, need more steps to process this request.`,name:this.name,id:r.id})]}:{messages:[r]})}#a(){if(typeof this.#e.model==`string`)return In(this.#e.model);if(this.#e.model)return this.#e.model;throw Error("No model option was provided, either via `model` option.")}async#o(e,t,n={}){let r=await this.#a(),i=t,a=async e=>{af(e.model);let r=this.#r(e.model),i=await this.#d(e.model,e,r),a=[...this.#n.text===``?[]:[this.#n],...e.messages],o=hf(this.#e.signal,t.signal),s=await Fe(i.invoke(a,{...t,signal:o}),o);if(r?.type===`native`){let e=r.strategy.parse(s);return e?{structuredResponse:e,messages:[s]}:s}if(!r||!s.tool_calls)return s;let c=s.tool_calls.filter(e=>e.name in r.tools);if(c.length===0)return s;if(c.length>1)return this.#s(s,c,r);let l=r.tools[c[0].name]?.options?.toolMessageContent;return this.#c(s,c[0],r,l??n.lastMessage)},o=this.#e.wrapModelCallHookMiddleware??[],s=a;for(let t=o.length-1;t>=0;t--){let[n,r]=o[t];if(n.wrapModelCall){let t=s,a=n,o=r;s=async r=>{let s=a.contextSchema?Re(a.contextSchema,i?.context||{}):i?.context,c=Object.freeze({context:s,writer:i.writer,interrupt:i.interrupt,signal:i.signal}),l={...r,state:{...n.stateSchema?Re(pf(n.stateSchema),e):{},...o(),messages:e.messages},runtime:c},u=async e=>{let n=e.tools??[],r=n.filter(e=>tf(e)&&!this.#e.toolClasses.some(t=>t.name===e.name));if(r.length>0)throw Error(`You have added a new tool in "wrapModelCall" hook of middleware "${a.name}": ${r.map(e=>e.name).join(`, `)}. This is not supported.`);let i=n.filter(e=>tf(e)&&this.#e.toolClasses.every(t=>t!==e));if(i.length>0)throw Error(`You have modified a tool in "wrapModelCall" hook of middleware "${a.name}": ${i.map(e=>e.name).join(`, `)}. This is not supported.`);let o=e,s=e.systemPrompt!==this.#n.text,c=e.systemMessage!==this.#n;if(s&&c)throw Error(`Cannot change both systemPrompt and systemMessage in the same request.`);return s&&(this.#n=new D({content:[{type:`text`,text:e.systemPrompt}]}),o={...e,systemPrompt:this.#n.text,systemMessage:this.#n}),c&&(this.#n=new D({...e.systemMessage}),o={...e,systemPrompt:this.#n.text,systemMessage:this.#n}),t(o)};if(!a.wrapModelCall)return u(l);try{let e=await a.wrapModelCall(l,u);if(!vf(e))throw Error(`Invalid response from "wrapModelCall" in middleware "${a.name}": expected AIMessage, got ${typeof e}`);return e}catch(e){throw Dd.wrap(e,a.name)}}}}this.#n=this.#t;let c={model:r,systemPrompt:this.#n?.text,systemMessage:this.#n,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:i?.context,writer:i.writer,interrupt:i.interrupt,signal:i.signal})};return s(c)}#s(e,t,n){let r=new wd(t.map(e=>e.name));return this.#l(r,e,t[0],n)}#c(e,t,n,r){let i=n.tools[t.name];try{let n=i.parse(t.args);return{structuredResponse:n,messages:[e,new A({tool_call_id:t.id??``,content:JSON.stringify(n),name:t.name}),new w(r??`Returning structured response: ${JSON.stringify(n)}`)]}}catch(r){return this.#l(r,e,t,n)}}async#l(e,t,n,r){let i=Object.values(r.tools).at(0)?.options?.handleError,a=n.id;if(!a)throw Error(`Tool call ID is required to handle tool output errors. Please provide a tool call ID.`);if(i===!1)throw e;if(i===void 0||typeof i==`boolean`&&i||Array.isArray(i)&&i.some(e=>e instanceof wd))return new W({update:{messages:[t,new A({content:e.message,tool_call_id:a})]},goto:$});if(typeof i==`string`)return new W({update:{messages:[t,new A({content:i,tool_call_id:a})]},goto:$});if(typeof i==`function`){let n=await i(e);if(typeof n!=`string`)throw Error(`Error handler must return a string.`);return new W({update:{messages:[t,new A({content:n,tool_call_id:a})]},goto:$})}return new W({update:{messages:[t,new A({content:e.message,tool_call_id:a})]},goto:$})}#u(e,t){let n=w.isInstance(t)&&t.tool_calls?.every(e=>this.#e.shouldReturnDirect.has(e.name)),r=`remainingSteps`in e?e.remainingSteps:void 0;return!!(r&&(r<1&&n||r<2&&of(e.messages.at(-1))))}async#d(e,t,n){let i={},a=Object.values(n&&`tools`in n?n.tools:{}),o=[...t?.tools??this.#e.toolClasses,...a.map(e=>e.tool)],s=t?.toolChoice||(a.length>0?`any`:void 0);if(n?.type===`native`){let e=t?.modelSettings?.strict??n?.strategy?.strict??!0,a={name:n.strategy.schema?.name??`extract`,description:r(n.strategy.schema),schema:n.strategy.schema,strict:e};Object.assign(i,{response_format:{type:`json_schema`,json_schema:a},output_format:{type:`json_schema`,schema:n.strategy.schema},headers:{"anthropic-beta":`structured-outputs-2025-11-13`},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:n.strategy.schema},strict:e})}let c=await cf(e,o,{...i,...t?.modelSettings,tool_choice:s});return this.#e.includeAgentName===`inline`?_f(c,this.#e.includeAgentName):c}getState(){let e=super.getState();return{messages:[],...e&&!(e instanceof W)?e:{}}}},bf=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(`, `)}].`,xf=`tools`,Sf=e=>Array.isArray(e)&&e.every(gt.isInstance),Cf=e=>typeof e==`object`&&!!e&&`messages`in e&&Sf(e.messages),wf=e=>typeof e==`object`&&!!e&&`lg_tool_call`in e;function Tf(e,t){return e instanceof Ed?new A({content:e.message,tool_call_id:t.id,name:t.name}):new A({content:`${e}\n Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var Ef=class extends gf{tools;trace=!1;signal;handleToolErrors=Tf;wrapToolCall;constructor(e,t){let{name:n,tags:r,handleToolErrors:i,signal:a,wrapToolCall:o}=t??{};super({name:n,tags:r,func:(e,t)=>this.run(e,t)}),this.options=t,this.tools=e,this.handleToolErrors=i??this.handleToolErrors,this.signal=a,this.wrapToolCall=o}#e(e,t,n){if(Jn(e)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors==`function`){let n=this.handleToolErrors(e,t);if(n&&A.isInstance(n))return n;throw e}else if(this.handleToolErrors)return new A({name:t.name,content:`${e}\n Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,n){let r=t,i={context:r?.context,writer:r?.writer,interrupt:r?.interrupt,signal:r?.signal},a=this.tools.find(t=>t.name===e.name),o=async e=>{let{toolCall:n,tool:r}=e,i=r??this.tools.find(e=>e.name===n.name);if(i===void 0){let e=this.tools.map(e=>e.name);return new A({content:bf(n.name,e),tool_call_id:n.id,name:n.name,status:`error`})}let a=i;try{let e=await a.invoke({...n,type:`tool_call`},{...t,config:t,toolCallId:n.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:hf(this.signal,t.signal)});return A.isInstance(e)||G(e)?e:new A({name:a.name,content:typeof e==`string`?e:JSON.stringify(e),tool_call_id:n.id})}catch(e){throw e instanceof Xe?new Ed(e,n):e}},s={toolCall:e,tool:a,state:n,runtime:i};if(this.wrapToolCall)try{return await this.wrapToolCall(s,o)}catch(t){return this.#e(t,e,!0)}if(!a){let t=this.tools.map(e=>e.name);return new A({content:bf(e.name,t),tool_call_id:e.id,name:e.name,status:`error`})}try{return await o(s)}catch(t){return this.#e(t,e,!1)}}async run(e,t){let n;if(wf(e)){let{lg_tool_call:r,jumpTo:i,...a}=e;n=[await this.runTool(e.lg_tool_call,t,a)]}else{let r;if(Sf(e))r=e;else if(Cf(e))r=e.messages;else throw Error(`ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.`);let i=new Set(r.filter(e=>e.getType()===`tool`).map(e=>e.tool_call_id)),a;for(let e=r.length-1;e>=0;--e){let t=r[e];if(w.isInstance(t)){a=t;break}}if(!w.isInstance(a))throw Error(`ToolNode only accepts AIMessages as input.`);n=await Promise.all(a.tool_calls?.filter(e=>e.id==null||!i.has(e.id)).map(n=>this.runTool(n,t,e))??[])}if(!n.some(G))return Array.isArray(e)?n:{messages:n};let r=[],i=null;for(let t of n)G(t)?t.graph===W.PARENT&&Array.isArray(t.goto)&&t.goto.every(e=>Df(e))?i?i.goto.push(...t.goto):i=new W({graph:W.PARENT,goto:t.goto}):r.push(t):r.push(Array.isArray(e)?[t]:{messages:[t]});return i&&r.push(i),r}};function Df(e){return e instanceof H}var Of=class{},kf=class{},Af=class extends gf{#e;constructor(e,t){super(e),this.#e=t}async invokeMiddleware(e,t){let n={};if(this.middleware.contextSchema){let e=this.middleware.contextSchema?.shape;if(e){let r={},i=t?.context||{};for(let t of Object.keys(e))t in i&&(r[t]=i[t]);n=Re(this.middleware.contextSchema,r)}}let r={...this.#e.getState(),...e,messages:e.messages},i={context:n,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},a=await this.runHook(r,Object.freeze(Object.assign(new kf,{...i,context:Object.freeze(Object.assign(new Of,n))})));if(!a)return{...r,jumpTo:void 0};let o,s;if(this.name?.startsWith(`BeforeAgentNode_`)?(o=Vd(this.middleware.beforeAgent),s=`beforeAgent.canJumpTo`):this.name?.startsWith(`BeforeModelNode_`)?(o=Vd(this.middleware.beforeModel),s=`beforeModel.canJumpTo`):this.name?.startsWith(`AfterAgentNode_`)?(o=Vd(this.middleware.afterAgent),s=`afterAgent.canJumpTo`):this.name?.startsWith(`AfterModelNode_`)&&(o=Vd(this.middleware.afterModel),s=`afterModel.canJumpTo`),typeof a.jumpTo==`string`&&!o?.includes(a.jumpTo)){let e=o&&o.length>0?`must be one of: ${o?.join(`, `)}.`:s?`no ${s} defined in middleware ${this.middleware.name}`:``;throw Error(`Invalid jump target: ${a.jumpTo}, ${e}.`)}if(typeof a==`object`&&`type`in a){if(a.type===`terminate`){if(a.error)throw a.error;return{...r,...a.result||{},jumpTo:a.jumpTo}}throw Error(`Invalid control action: ${JSON.stringify(a)}`)}return{...r,...a,jumpTo:a.jumpTo}}get nodeOptions(){return{input:ff(this.middleware.stateSchema)}}},jf=class extends Af{lc_namespace=[`langchain`,`agents`,`beforeAgentNodes`];constructor(e,t){super({name:`BeforeAgentNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.beforeAgent)(e,t)}},Mf=class extends Af{lc_namespace=[`langchain`,`agents`,`beforeModelNodes`];constructor(e,t){super({name:`BeforeModelNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.beforeModel)(e,t)}},Nf=class extends Af{lc_namespace=[`langchain`,`agents`,`afterModelNodes`];constructor(e,t){super({name:`AfterModelNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.afterModel)(e,t)}},Pf=class extends Af{lc_namespace=[`langchain`,`agents`,`afterAgentNodes`];constructor(e,t){super({name:`AfterAgentNode_${e.name}`,func:async(e,t)=>this.invokeMiddleware(e,t)},t),this.middleware=e}runHook(e,t){return Hd(this.middleware.afterAgent)(e,t)}},Ff=class{#e=new Map;addNode(e,t){this.#e.set(e.name,[...this.#e.get(e.name)??[],t])}getState(e){let t=(this.#e.get(e)??[]).reduce((e,t)=>({...e,...t.getState()??{}}),{});return delete t.jumpTo,t}},If=class{#e;#t=`v2`;#n;#r=new Ff;constructor(e){if(this.options=e,this.#t=e.version??this.#t,!e.model)throw Error("`model` option is required to create an agent.");typeof e.model!=`string`&&af(e.model);let t=this.options.middleware?.filter(e=>e.tools).flatMap(e=>e.tools)??[],n=[...e.tools??[],...t],r=new Set(n.filter(tf).filter(e=>`returnDirect`in e&&e.returnDirect).map(e=>e.name)),{state:i,input:a,output:o}=Yd(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),s=new hd(i,{input:a,output:o,context:this.options.contextSchema}),c=[],l=[],u=[],d=[],f=[];this.#n=new yf({model:this.options.model,systemMessage:sf(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:n,shouldReturnDirect:r,signal:this.options.signal,wrapModelCallHookMiddleware:f});let p=new Set,m=this.options.middleware??[];for(let e=0;e<m.length;e++){let t,n,r,i,a=m[e];if(p.has(a.name))throw Error(`Middleware ${a.name} is defined multiple times`);if(p.add(a.name),a.beforeAgent){t=new jf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,t);let n=`${a.name}.before_agent`;c.push({index:e,name:n,allowed:Vd(a.beforeAgent)}),s.addNode(n,t,t.nodeOptions)}if(a.beforeModel){n=new Mf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,n);let t=`${a.name}.before_model`;l.push({index:e,name:t,allowed:Vd(a.beforeModel)}),s.addNode(t,n,n.nodeOptions)}if(a.afterModel){r=new Nf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,r);let t=`${a.name}.after_model`;u.push({index:e,name:t,allowed:Vd(a.afterModel)}),s.addNode(t,r,r.nodeOptions)}if(a.afterAgent){i=new Pf(a,{getState:()=>this.#r.getState(a.name)}),this.#r.addNode(a,i);let t=`${a.name}.after_agent`;d.push({index:e,name:t,allowed:Vd(a.afterAgent)}),s.addNode(t,i,i.nodeOptions)}a.wrapModelCall&&f.push([a,()=>this.#r.getState(a.name)])}s.addNode($,this.#n);let h=m.some(e=>e.wrapToolCall),g=n.filter(tf);if(g.length>0||h){let e=new Ef(g,{signal:this.options.signal,wrapToolCall:uf(m)});s.addNode(xf,e)}let _;_=c.length>0?c[0].name:l.length>0?l[0].name:$;let v=l.length>0?l[0].name:$,y=d.length>0?d[d.length-1].name:z;s.addEdge(R,_);let b=g.length>0||h;for(let e=0;e<c.length;e++){let t=c[e],n=t.name,r=e===c.length-1?v:c[e+1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e.map(e=>e===`__end__`?y:e)]));s.addConditionalEdges(n,this.#l(g,r,y,b),i)}else s.addEdge(n,r)}for(let e=0;e<l.length;e++){let t=l[e],n=t.name,r=e===l.length-1?$:l[e+1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e]));s.addConditionalEdges(n,this.#u(g,r,b),i)}else s.addEdge(n,r)}let x=u.at(-1);if(u.length>0&&x)s.addEdge($,x.name);else{let e=this.#i(g,!1,b).map(e=>e===`__end__`?y:e);e.length===1?s.addEdge($,e[0]):s.addConditionalEdges($,this.#o(y),e)}for(let e=u.length-1;e>0;e--){let t=u[e],n=t.name,r=u[e-1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e]));s.addConditionalEdges(n,this.#c(g,t.allowed,r,b),i)}else s.addEdge(n,r)}if(u.length>0){let e=u[0],t=e.name,n=this.#i(g,!0,b).filter(e=>e!==`tools`||b),r=!!(e.allowed&&e.allowed.length>0),i=n.map(e=>e===`__end__`?y:e);s.addConditionalEdges(t,this.#s(g,r,y,b),i)}for(let e=d.length-1;e>0;e--){let t=d[e],n=t.name,r=d[e-1].name;if(t.allowed&&t.allowed.length>0){let e=t.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),i=Array.from(new Set([r,...e]));s.addConditionalEdges(n,this.#c(g,t.allowed,r,b),i)}else s.addEdge(n,r)}if(d.length>0){let e=d[0],t=e.name;if(e.allowed&&e.allowed.length>0){let n=e.allowed.map(e=>mf(e)).filter(e=>e!==`tools`||b),r=Array.from(new Set([z,...n]));s.addConditionalEdges(t,this.#c(g,e.allowed,z,b),r)}else s.addEdge(t,z)}if(b){let e=v;r.size>0?s.addConditionalEdges(xf,this.#a(r,y),[e,y]):s.addEdge(xf,e)}this.#e=s.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}#i(e,t=!1,n=e.length>0){let r=[];return n&&r.push(xf),t&&r.push($),r.push(z),r}#a(e,t){return n=>{let r=n.messages,i=r[r.length-1];return A.isInstance(i)&&i.name&&e.has(i.name)?this.options.responseFormat?$:t:$}}#o(e=z){return t=>{let n=t.messages.at(-1);if(!w.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(e=>e.name.startsWith(`extract-`)))return e;if(this.#t===`v1`)return xf;let r=n.tool_calls.filter(e=>!e.name.startsWith(`extract-`));return r.length===0?e:r.map(e=>new H(xf,{...t,lg_tool_call:e}))}}#s(e,t,n,r=e.length>0){let i=!!this.options.responseFormat;return e=>{let a=e,o=a.messages,s=o.at(-1);if(w.isInstance(s)&&(!s.tool_calls||s.tool_calls.length===0))return n;if(t&&a.jumpTo){let t=mf(a.jumpTo);return t===`__end__`?n:t===`tools`?r?new H(xf,{...e,jumpTo:void 0}):n:new H($,{...e,jumpTo:void 0})}let c=o.filter(A.isInstance),l=o.filter(w.isInstance).at(-1),u=l?.tool_calls?.filter(e=>!c.some(t=>t.tool_call_id===e.id));if(u&&u.length>0)return u.map(t=>new H(xf,{...e,lg_tool_call:t}));let d=l?.tool_calls?.some(e=>e.name.startsWith(`extract-`));if(u&&u.length===0&&!d&&i)return $;if(!w.isInstance(s)||!s.tool_calls||s.tool_calls.length===0)return n;let f=s.tool_calls.every(e=>e.name.startsWith(`extract-`)),p=s.tool_calls.some(e=>!e.name.startsWith(`extract-`));return f||!p?n:xf}}#c(e,t,n,r=e.length>0){let i=new Set(t.map(e=>mf(e)));return e=>{let t=e;if(t.jumpTo){let n=mf(t.jumpTo);if(n===`__end__`&&i.has(`__end__`))return z;if(n===`tools`&&i.has(`tools`))return r?new H(xf,{...e,jumpTo:void 0}):z;if(n===`model_request`&&i.has(`model_request`))return new H($,{...e,jumpTo:void 0})}return n}}#l(e,t,n,r=e.length>0){return e=>{let i=e;if(!i.jumpTo)return t;let a=mf(i.jumpTo);return a===`__end__`?n:a===`tools`?r?new H(xf,{...e,jumpTo:void 0}):n:new H($,{...e,jumpTo:void 0})}}#u(e,t,n=e.length>0){return e=>{let r=e;if(!r.jumpTo)return t;let i=mf(r.jumpTo);return i===`__end__`?z:i===`tools`?n?new H(xf,{...e,jumpTo:void 0}):z:new H($,{...e,jumpTo:void 0})}}async#d(e,t){if(!this.options.middleware||this.options.middleware.length===0||e instanceof W||!e)return e;let n=await df(this.options.middleware,e),r={...(await this.#e.getState(t).catch(()=>({values:{}}))).values,...e};if(!r)return r;for(let[e,t]of Object.entries(n))e in r||(r[e]=t);return r}async invoke(e,t){let n=await this.#d(e,t);return this.#e.invoke(n,t)}async stream(e,t){let n=await this.#d(e,t);return this.#e.stream(n,t)}async drawMermaidPng(e){let t=await(await(await this.#e.getGraphAsync()).drawMermaidPng(e)).arrayBuffer();return new Uint8Array(t)}async drawMermaid(e){return(await this.#e.getGraphAsync()).drawMermaid(e)}streamEvents(e,t,n){return this.#e.streamEvents(e,{...t,version:t?.version??`v2`},n)}getGraphAsync(e){return this.#e.getGraphAsync(e)}getState(e,t){return this.#e.getState(e,t)}getStateHistory(e,t){return this.#e.getStateHistory(e,t)}getSubgraphs(e,t){return this.#e.getSubgraphs(e,t)}getSubgraphAsync(e,t){return this.#e.getSubgraphsAsync(e,t)}updateState(e,t,n){return this.#e.updateState(e,t,n)}get builder(){return this.#e.builder}};function Lf(e){return new If(e)}var Rf=Qe().args(h(),h(),h()).returns(st([k(),ue(k())])),zf=[`approve`,`edit`,`reject`],Bf=T({allowedDecisions:ve(ee(zf)),description:st([k(),Rf]).optional(),argsSchema:n(v()).optional()}),Vf=T({interruptOn:n(st([xe(),Bf])).optional(),descriptionPrefix:k().default(`Tool execution requires approval`)});function Hf(e){let t=async(t,n,r,i)=>{let a=t.name,o=t.args,s=n.description,c;c=typeof s==`function`?await s(t,r,i):s===void 0?`${e.descriptionPrefix??`Tool execution requires approval`}\n\nTool: ${a}\nArgs: ${JSON.stringify(o,null,2)}`:s;let l={name:a,args:o,description:c},u={actionName:a,allowedDecisions:n.allowedDecisions};return n.argsSchema&&(u.argsSchema=n.argsSchema),{actionRequest:l,reviewConfig:u}},n=(e,t,n)=>{let r=n.allowedDecisions;if(e.type===`approve`&&r.includes(`approve`))return{revisedToolCall:t,toolMessage:null};if(e.type===`edit`&&r.includes(`edit`)){let n=e.editedAction;if(!n||typeof n.name!=`string`)throw Error(`Invalid edited action for tool "${t.name}": name must be a string`);if(!n.args||typeof n.args!=`object`)throw Error(`Invalid edited action for tool "${t.name}": args must be an object`);return{revisedToolCall:{type:`tool_call`,name:n.name,args:n.args,id:t.id},toolMessage:null}}if(e.type===`reject`&&r.includes(`reject`)){if(e.message!==void 0&&typeof e.message!=`string`)throw Error(`Tool call response for "${t.name}" must be a string, got ${typeof e.message}`);return{revisedToolCall:t,toolMessage:new A({content:e.message??`User rejected the tool call for \`${t.name}\` with id ${t.id}`,name:t.name,tool_call_id:t.id,status:`error`})}}let i=`Unexpected human decision: ${JSON.stringify(e)}. Decision type '${e.type}' is not allowed for tool '${t.name}'. Expected one of ${JSON.stringify(r)} based on the tool's configuration.`;throw Error(i)};return Q({name:`HumanInTheLoopMiddleware`,contextSchema:Vf,afterModel:{canJumpTo:[`model`],hook:async(r,i)=>{let a=Re(Vf,{...e,...i.context||{}});if(!a)return;let{messages:o}=r;if(!o.length)return;let s=[...o].reverse().find(e=>w.isInstance(e));if(!s||!s.tool_calls?.length||!a.interruptOn)return;let c={};for(let[e,t]of Object.entries(a.interruptOn))typeof t==`boolean`?t===!0&&(c[e]={allowedDecisions:[...zf]}):t.allowedDecisions&&(c[e]=t);let l=[],u=[];for(let e of s.tool_calls)e.name in c?l.push(e):u.push(e);if(!l.length)return;let d=[],f=[];for(let e of l){let n=c[e.name],{actionRequest:a,reviewConfig:o}=await t(e,n,r,i);d.push(a),f.push(o)}let p=(await Qc({actionRequests:d,reviewConfigs:f})).decisions;if(!p||!Array.isArray(p))throw Error(`Invalid HITLResponse: decisions must be a non-empty array`);if(p.length!==l.length)throw Error(`Number of human decisions (${p.length}) does not match number of hanging tool calls (${l.length}).`);let m=[...u],h=[],g=p.some(e=>e.type===`reject`);for(let e=0;e<p.length;e++){let t=p[e],r=l[e],i=c[r.name],{revisedToolCall:a,toolMessage:o}=n(t,r,i);a&&(!g||t.type===`reject`)&&m.push(a),o&&h.push(o)}w.isInstance(s)&&(s.tool_calls=m);let _=g?`model`:void 0;return{messages:[s,...h],jumpTo:_}}}})}var Uf=`<role>
|
|
31
31
|
Context Extraction Assistant
|
|
32
32
|
</role>
|
|
33
33
|
|
|
@@ -53,7 +53,7 @@ Respond ONLY with the extracted context. Do not include any additional informati
|
|
|
53
53
|
<messages>
|
|
54
54
|
Messages to summarize:
|
|
55
55
|
{messages}
|
|
56
|
-
</messages>`,Wf=`Here is a summary of the conversation to date:`,Gf=20,Kf=4e3,qf=15,Jf=5,Yf
|
|
56
|
+
</messages>`,Wf=`Here is a summary of the conversation to date:`,Gf=20,Kf=4e3,qf=15,Jf=5,Yf=Qe().args(ve(h())).returns(st([C(),ue(C())])),Xf=T({fraction:C().gt(0,`Fraction must be greater than 0`).max(1,`Fraction must be less than or equal to 1`).optional(),tokens:C().positive(`Tokens must be greater than 0`).optional(),messages:C().int(`Messages must be an integer`).positive(`Messages must be greater than 0`).optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(e=>e!==void 0).length>=1,{message:`At least one of fraction, tokens, or messages must be provided`}),Zf=T({fraction:C().min(0,`Messages must be non-negative`).max(1,`Fraction must be less than or equal to 1`).optional(),tokens:C().min(0,`Tokens must be greater than or equal to 0`).optional(),messages:C().int(`Messages must be an integer`).min(0,`Messages must be non-negative`).optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(e=>e!==void 0).length===1,{message:`Exactly one of fraction, tokens, or messages must be provided`}),Qf=T({model:h(),trigger:st([Xf,ve(Xf)]).optional(),keep:Zf.optional(),tokenCounter:Yf.optional(),summaryPrompt:k().default(Uf),trimTokensToSummarize:C().optional(),summaryPrefix:k().optional(),maxTokensBeforeSummary:C().optional(),messagesToKeep:C().optional()});function $f(e){if(`profile`in e&&typeof e.profile==`object`&&e.profile&&`maxInputTokens`in e.profile&&(typeof e.profile.maxInputTokens==`number`||e.profile.maxInputTokens==null))return e.profile.maxInputTokens??void 0;if(`model`in e&&typeof e.model==`string`)return Ut(e.model);if(`modelName`in e&&typeof e.modelName==`string`)return Ut(e.modelName)}function ep(e){let{data:t,error:n}=re(Qf,e);if(n)throw Error(`Invalid summarization middleware options: ${wt(n)}`);return Q({name:`SummarizationMiddleware`,contextSchema:Qf.extend({model:h().optional()}),beforeModel:async(e,n)=>{let r=t.trigger,i=t.keep;t.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),r===void 0&&(r={tokens:t.maxTokensBeforeSummary})),t.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&`messages`in i&&i.messages===Gf)&&(i={messages:t.messagesToKeep}));let a=n.context?.trigger===void 0?r:n.context.trigger,o=n.context?.keep===void 0?i??{messages:Gf}:n.context.keep,s=Zf.parse(o),c=[];c=a===void 0?[]:Array.isArray(a)?a.map(e=>Xf.parse(e)):[Xf.parse(a)];let l=c.some(e=>`fraction`in e)||`fraction`in s,u=typeof t.model==`string`?await In(t.model):t.model;if(l&&!$f(u))throw Error(`Model profile information is required to use fractional token limits. Use absolute token counts instead.`);let d=n.context?.summaryPrompt===Uf?t.summaryPrompt??Uf:n.context?.summaryPrompt??t.summaryPrompt??Uf,f=n.context.summaryPrefix??t.summaryPrefix??Wf,p=n.context?.trimTokensToSummarize===void 0?t.trimTokensToSummarize??Kf:n.context.trimTokensToSummarize;tp(e.messages);let m=n.context?.tokenCounter===void 0?t.tokenCounter??Bd:n.context.tokenCounter,h=await m(e.messages);if(!await ip(e.messages,h,c,u))return;let{systemPrompt:g,conversationMessages:_}=np(e.messages),v=await ap(_,s,m,u);if(v<=0)return;let{messagesToSummarize:y,preservedMessages:b}=rp(g,_,v),x=new O({content:`${f}\n\n${await fp(y,u,d,m,p,n)}`,id:te(),additional_kwargs:{lc_source:`summarization`}});return{messages:[new lt({id:od}),x,...b]}}})}function tp(e){for(let t of e)t.id||=te()}function np(e){return e.length>0&&D.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function rp(e,t,n){let r=t.slice(0,n),i=t.slice(n);return e&&r.unshift(e),{messagesToSummarize:r,preservedMessages:i}}async function ip(e,t,n,r){if(n.length===0)return!1;for(let i of n){let n=!0,a=!1;if(i.messages!==void 0&&(a=!0,e.length<i.messages&&(n=!1)),i.tokens!==void 0&&(a=!0,t<i.tokens&&(n=!1)),i.fraction!==void 0){a=!0;let e=$f(r);typeof e==`number`?t<Math.floor(e*i.fraction)&&(n=!1):n=!1}if(a&&n)return!0}return!1}async function ap(e,t,n,r){if(`tokens`in t||`fraction`in t){let i=await op(e,t,n,r);return typeof i==`number`?i:sp(e,Gf)}return sp(e,t.messages??Gf)}async function op(e,t,n,r){if(e.length===0)return 0;let i;if(`fraction`in t&&t.fraction!==void 0){let e=$f(r);if(typeof e!=`number`)return;i=Math.floor(e*t.fraction)}else if(`tokens`in t&&t.tokens!==void 0)i=Math.floor(t.tokens);else return;if(i<=0&&(i=1),await n(e)<=i)return 0;let a=0,o=e.length,s=e.length,c=Math.floor(Math.log2(e.length))+1;for(let t=0;t<c&&!(a>=o);t++){let t=Math.floor((a+o)/2);await n(e.slice(t))<=i?(s=t,o=t):a=t+1}if(s===e.length&&(s=a),s>=e.length){if(e.length===1)return 0;s=e.length-1}let l=up(e,s);if(l<=s)return l;for(let t=s;t>=0;t--)if(cp(e,t))return t;return 0}function sp(e,t){if(e.length<=t)return 0;let n=e.length-t,r=up(e,n);if(r<=n)return r;for(let t=n;t>=0;t--)if(cp(e,t))return t;return 0}function cp(e,t){if(t>=e.length)return!0;if(t<e.length&&w.isInstance(e[t])&&of(e[t]))return!1;let n=Math.max(0,t-Jf),r=Math.min(e.length,t+Jf);for(let i=n;i<r;i++){if(!of(e[i]))continue;let n=lp(e[i]);if(dp(e,i,t,n))return!1}return!0}function lp(e){let t=new Set;if(e.tool_calls)for(let n of e.tool_calls){let e=typeof n==`object`&&`id`in n?n.id:null;e&&t.add(e)}return t}function up(e,t){if(t>=e.length||!A.isInstance(e[t]))return t;let n=new Set,r=t;for(;r<e.length&&A.isInstance(e[r]);){let t=e[r];t.tool_call_id&&n.add(t.tool_call_id),r++}for(let r=t-1;r>=0;r--){let t=e[r];if(w.isInstance(t)&&of(t)){let e=lp(t);for(let t of n)if(e.has(t))return r}}return r}function dp(e,t,n,r){for(let i=t+1;i<e.length;i++){let a=e[i];if(A.isInstance(a)&&r.has(a.tool_call_id)&&t<n!=i<n)return!0}return!1}async function fp(e,t,n,r,i,a){if(!e.length)return`No previous conversation history.`;let o=await pp(e,r,i);if(!o.length)return`Previous conversation was too long to summarize.`;let s=$e(o);try{let e=n.replace(`{messages}`,s),r=bt(_t(a)??{},{metadata:{lc_source:`summarization`}}),i=(await t.invoke(e,r)).content;return typeof i==`string`?i.trim():Array.isArray(i)?i.map(e=>typeof e==`string`?e:typeof e==`object`&&e&&`text`in e?e.text:``).join(``).trim():`Error generating summary: Invalid response format`}catch(e){return`Error generating summary: ${e}`}}async function pp(e,t,n){if(n===void 0)return e;try{return await Ie(e,{maxTokens:n,tokenCounter:async e=>t(e),strategy:`last`,allowPartial:!0,includeSystem:!0})}catch{return e.slice(-qf)}}function mp(e){return Q({name:`DynamicSystemPromptMiddleware`,wrapModelCall:async(t,n)=>{let r=await e(t.state,t.runtime);if(!(typeof r==`string`||D.isInstance(r)))throw Error(`dynamicSystemPromptMiddleware function must return a string or SystemMessage`);return n({...t,systemMessage:t.systemMessage.concat(r)})}})}var hp=`Your goal is to select the most relevant tools for answering the user's query.`;function gp(e){if(!e||e.length===0)throw Error(`Invalid usage: tools must be non-empty`);return T({tools:ve(st(e.map(e=>Ce(e.name)))).describe(`Tools to use. Place the most relevant tools first.`)})}var _p=T({model:k().or(S(Zt)).optional(),systemPrompt:k().optional(),maxTools:C().optional(),alwaysInclude:ve(k()).optional()});function vp(e){return Q({name:`LLMToolSelector`,contextSchema:_p,async wrapModelCall(t,n){let r=await yp(t,e,t.runtime);if(!r)return n(t);let i=gp(r.availableTools),a=await(await r.model.withStructuredOutput?.(i))?.invoke([{role:`system`,content:r.systemMessage},r.lastUserMessage]);if(!a||typeof a!=`object`||!(`tools`in a))throw Error(`Expected object response with tools array, got ${typeof a}`);return n(bp(a,r.availableTools,r.validToolNames,t,e))}})}async function yp(e,t,n){let r=n.context.model??t.model,i=n.context.maxTools??t.maxTools,a=n.context.alwaysInclude??t.alwaysInclude??[],o=n.context.systemPrompt??t.systemPrompt??hp;if(!e.tools||e.tools.length===0)return;let s=e.tools.filter(e=>typeof e==`object`&&`name`in e&&`description`in e&&typeof e.name==`string`);if(a.length>0){let e=new Set(s.map(e=>e.name)),t=a.filter(t=>!e.has(t));if(t.length>0)throw Error(`Tools in alwaysInclude not found in request: ${t.join(`, `)}. Available tools: ${Array.from(e).sort().join(`, `)}`)}let c=s.filter(e=>!a.includes(e.name));if(c.length===0)return;let l=o;i!==void 0&&(l+=`
|
|
57
57
|
IMPORTANT: List the tool names in order of relevance, with the most relevant first. If you exceed the maximum number of tools, only the first ${i} will be used.`);let u;for(let t of e.messages)O.isInstance(t)&&(u=t);if(!u)throw Error(`No user message found in request messages`);let d=r?typeof r==`string`?await In(r):r:e.model,f=c.map(e=>e.name);return{availableTools:c,systemMessage:l,lastUserMessage:u,model:d,validToolNames:f}}function bp(e,t,n,r,i){let a=i.maxTools,o=i.alwaysInclude??[],s=[],c=[];for(let t of e.tools){if(!n.includes(t)){c.push(t);continue}!s.includes(t)&&(a===void 0||s.length<a)&&s.push(t)}if(c.length>0)throw Error(`Model selected invalid tools: ${c.join(`, `)}`);let l=t.filter(e=>s.includes(e.name)),u=(r.tools??[]).filter(e=>typeof e==`object`&&`name`in e&&typeof e.name==`string`&&o.includes(e.name));l.push(...u);let d=(r.tools??[]).filter(e=>!(typeof e==`object`&&`name`in e&&`description`in e&&typeof e.name==`string`));return{...r,tools:[...l,...d]}}var xp=class extends Error{constructor(e,t){super(`PII detected: ${e} found ${t.length} occurrence(s)`),this.piiType=e,this.matches=t,this.name=`PIIDetectionError`}},Sp=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,Cp=/\b(?:\d{4}[-\s]?){3}\d{4}\b/g,wp=/\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g,Tp=/\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\b/g,Ep=/(?:https?:\/\/|www\.)[^\s<>"{}|\\^`[\]]+/gi;function Dp(e){let t=e.replace(/\D/g,``),n=0,r=!1;for(let e=t.length-1;e>=0;e--){let i=parseInt(t[e],10);r&&(i*=2,i>9&&(i-=9)),n+=i,r=!r}return n%10==0}function Op(e){return{text:e[0],start:e.index??0,end:(e.index??0)+e[0].length}}function kp(e){let t=[],n=new RegExp(Sp),r;for(;(r=n.exec(e))!==null;)t.push(Op(r));return t}function Ap(e){let t=[],n=new RegExp(Cp),r;for(;(r=n.exec(e))!==null;){let e=r[0].replace(/\D/g,``);e.length>=13&&e.length<=19&&Dp(e)&&t.push(Op(r))}return t}function jp(e){let t=[],n=new RegExp(wp),r;for(;(r=n.exec(e))!==null;){let e=r[0].split(`.`);e.length===4&&e.every(e=>{let t=parseInt(e,10);return t>=0&&t<=255})&&t.push(Op(r))}return t}function Mp(e){let t=[],n=new RegExp(Tp),r;for(;(r=n.exec(e))!==null;)t.push(Op(r));return t}function Np(e){let t=[],n=new RegExp(Ep),r;for(;(r=n.exec(e))!==null;)t.push(Op(r));return t}var Pp={email:kp,credit_card:Ap,ip:jp,mac_address:Mp,url:Np};function Fp(e){let t;if(e.detector)if(typeof e.detector==`string`){let n=new RegExp(e.detector,`g`);t=e=>{let t=[],r,i=new RegExp(n);for(;(r=i.exec(e))!==null;)t.push(Op(r));return t}}else t=e.detector instanceof RegExp?t=>{if(!(e.detector instanceof RegExp))throw Error(`Detector is required`);let n=[],r;for(;(r=e.detector.exec(t))!==null;)n.push(Op(r));return n}:e.detector;else{let n=e.piiType;if(!Pp[n])throw Error(`Unknown PII type: ${e.piiType}. Must be one of: ${Object.keys(Pp).join(`, `)}, or provide a custom detector.`);t=Pp[n]}return{piiType:e.piiType,strategy:e.strategy,detector:t}}function Ip(e,t,n){let r=e;for(let e=t.length-1;e>=0;e--){let i=t[e],a=`[REDACTED_${n.toUpperCase()}]`;r=r.slice(0,i.start)+a+r.slice(i.end)}return r}function Lp(e,t,n){let r=e;for(let e=t.length-1;e>=0;e--){let i=t[e],a=i.text,o;if(n===`credit_card`)o=`****-****-****-${a.replace(/\D/g,``).slice(-4)}`;else if(n===`email`){let[e,t]=a.split(`@`);o=e&&t?`${e[0]}***@${t}`:`***`}else{let e=Math.min(4,a.length);o=`${`*`.repeat(Math.max(0,a.length-e))}${a.slice(-e)}`}r=r.slice(0,i.start)+o+r.slice(i.end)}return r}function Rp(e,t,n){let r=e;for(let e=t.length-1;e>=0;e--){let i=t[e],a=`<${n}_hash:${zt(i.text).slice(0,8)}>`;r=r.slice(0,i.start)+a+r.slice(i.end)}return r}function zp(e,t,n,r){if(t.length===0)return e;switch(n){case`block`:throw new xp(r,t);case`redact`:return Ip(e,t,r);case`mask`:return Lp(e,t,r);case`hash`:return Rp(e,t,r);default:throw Error(`Unknown strategy: ${n}`)}}var Bp=T({applyToInput:xe().optional(),applyToOutput:xe().optional(),applyToToolResults:xe().optional()});function Vp(e,t){let n=t.detector(e);return n.length===0?{content:e,matches:[]}:{content:zp(e,n,t.strategy,t.piiType),matches:n}}function Hp(e,t={}){let{strategy:n=`redact`,detector:r}=t,i=Fp({piiType:e,strategy:n,detector:r});return Q({name:`PIIMiddleware[${i.piiType}]`,contextSchema:Bp,beforeModel:async(e,n)=>{let r=n.context.applyToInput??t.applyToInput??!0,a=n.context.applyToToolResults??t.applyToToolResults??!1;if(!r&&!a)return;let o=e.messages;if(!o||o.length===0)return;let s=[...o],c=!1;if(r){let e=null;for(let t=o.length-1;t>=0;t--)if(O.isInstance(o[t])){e=t;break}if(e!==null){let t=o[e];if(t&&t.content){let{content:n,matches:r}=Vp(String(t.content),i);r.length>0&&(s[e]=new O({content:n,id:t.id,name:t.name}),c=!0)}}}if(a){let e=null;for(let t=o.length-1;t>=0;t--)if(w.isInstance(o[t])){e=t;break}if(e!==null)for(let t=e+1;t<o.length;t++){let e=o[t];if(A.isInstance(e)){if(!e.content)continue;let{content:n,matches:r}=Vp(String(e.content),i);r.length>0&&(s[t]=new A({content:n,id:e.id,name:e.name,tool_call_id:e.tool_call_id}),c=!0)}}}if(c)return{messages:s}},afterModel:async(e,n)=>{if(!(n.context.applyToOutput??t.applyToOutput??!1))return;let r=e.messages;if(!r||r.length===0)return;let a=null,o=null;for(let e=r.length-1;e>=0;e--)if(w.isInstance(r[e])){o=r[e],a=e;break}if(a===null||!o||!o.content)return;let{content:s,matches:c}=Vp(String(o.content),i);if(c.length===0)return;let l=new w({content:s,id:o.id,name:o.name,tool_calls:o.tool_calls}),u=[...r];return u[a]=l,{messages:u}}})}var Up=T({rules:n(k(),S(RegExp).describe(`Regular expression pattern to match PII`)).optional()});function Wp(){return Math.random().toString(36).substring(2,11)}function Gp(e,t,n){let r=e;for(let[e,i]of Object.entries(t)){let t=e.toUpperCase().replace(/[^a-zA-Z0-9_-]/g,``);r=r.replace(i,e=>{let r=Wp();return n[r]=e,`[REDACTED_${t}_${r}]`})}return r}async function Kp(e,t){if(O.isInstance(e)||A.isInstance(e)||D.isInstance(e)){let n=e.content,r=await Gp(n,t.rules,t.redactionMap);if(r!==n){let t=Object.getPrototypeOf(e).constructor;return new t({...e,content:r})}return e}if(w.isInstance(e)){let n=typeof e.content==`string`?e.content:JSON.stringify(e.content),r=JSON.stringify(e.tool_calls),i=await Gp(n,t.rules,t.redactionMap),a=await Gp(r,t.rules,t.redactionMap);return i!==n||a!==r?new w({...e,content:typeof e.content==`string`?i:JSON.parse(i),tool_calls:JSON.parse(a)}):e}throw Error(`Unsupported message type: ${e.type}`)}function qp(e,t){let n=e;return n=n.replace(/\[REDACTED_[A-Z_]+_(\w+)\]/g,(e,n)=>t[n]?t[n]:e),n}function Jp(e,t){if(O.isInstance(e)||A.isInstance(e)||D.isInstance(e)){let n=e.content,r=qp(n,t);if(r!==n){let t=Object.getPrototypeOf(e).constructor;return{message:new t({...e,content:r}),changed:!0}}return{message:e,changed:!1}}if(w.isInstance(e)){let n=typeof e.content==`string`?e.content:JSON.stringify(e.content),r=JSON.stringify(e.tool_calls),i=qp(n,t),a=qp(r,t);return i!==n||a!==r?{message:new w({...e,content:typeof e.content==`string`?i:JSON.parse(i),tool_calls:JSON.parse(a)}),changed:!0}:{message:e,changed:!1}}throw Error(`Unsupported message type: ${e.type}`)}function Yp(e={}){let t={};return console.warn(`DEPRECATED: piiRedactionMiddleware is deprecated. Please use piiMiddleware instead, go to https://docs.langchain.com/oss/javascript/langchain/middleware/built-in#pii-detection for more information.`),Q({name:`PIIRedactionMiddleware`,contextSchema:Up,wrapModelCall:async(n,r)=>{let i=n.runtime.context.rules??e.rules??{};if(Object.keys(i).length===0)return r(n);let a=await Promise.all(n.state.messages.map(e=>Kp(e,{rules:i,redactionMap:t})));return r({...n,messages:a})},afterModel:async e=>{if(Object.keys(t).length===0)return;let n=e.messages.at(-1);if(!w.isInstance(n))return;let r=e.messages.at(-2),{message:i,changed:a}=Jp(n,t);if(!a)return;let o;if(w.isInstance(n)&&n?.tool_calls?.length===0&&typeof n.content==`string`&&n.content.startsWith(`{`)&&n.content.endsWith(`}`))try{o=JSON.parse(qp(n.content,t))}catch{}if(w.isInstance(r)&&r?.tool_calls?.length!==0&&r?.tool_calls?.some(e=>e.name.startsWith(`extract-`))){let{message:o,changed:s}=Jp(r,t),c=r.tool_calls?.find(e=>e.name.startsWith(`extract-`))?.args,l=c?JSON.parse(qp(JSON.stringify(c),t)):void 0;if(a||s)return{...e,...l?{structuredResponse:l}:{},messages:[new lt({id:r.id}),new lt({id:n.id}),o,i]}}return{...e,...o?{structuredResponse:o}:{},messages:[new lt({id:n.id}),i]}}})}var Xp=`[cleared]`,Zp=1e5,Qp=3,$p=class{#e;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(e={}){let t=e.trigger;e.triggerTokens!==void 0&&(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),t===void 0&&(t={tokens:e.triggerTokens}));let n=e.keep;if(e.keepMessages!==void 0&&(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),n===void 0&&(n={messages:e.keepMessages})),t===void 0&&(t={tokens:Zp}),n===void 0&&(n={messages:Qp}),Array.isArray(t))this.#e=t.map(e=>Xf.parse(e)),this.trigger=this.#e;else{let e=Xf.parse(t);this.#e=[e],this.trigger=e}this.keep=Zf.parse(n),e.clearAtLeast!==void 0&&console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention."),this.clearAtLeast=e.clearAtLeast??0,this.clearToolInputs=e.clearToolInputs??!1,this.excludeTools=new Set(e.excludeTools??[]),this.placeholder=e.placeholder??Xp}async apply(e){let{messages:t,model:n,countTokens:r}=e,i=await r(t),a=[];for(let e=0;e<t.length;e++){let n=t[e];if(A.isInstance(n)){let r=this.#r(t.slice(0,e),n.tool_call_id);r&&r.tool_calls?.find(e=>e.id===n.tool_call_id)||a.push(e)}}for(let e=a.length-1;e>=0;e--)t.splice(a[e],1);let o=i;if(a.length>0&&(o=await r(t)),!this.#t(t,o,n))return;let s=[];for(let e=0;e<t.length;e++){let n=t[e];A.isInstance(n)&&s.push({idx:e,msg:n})}if(s.length===0)return;let c=await this.#n(s,r,n),l=c>=s.length?[]:c>0?s.slice(0,-c):s,u=0,d=[...l];for(let{idx:e,msg:n}of d){if(n.response_metadata?.context_editing?.cleared)continue;let i=this.#r(t.slice(0,e),n.tool_call_id);if(!i)continue;let a=i.tool_calls?.find(e=>e.id===n.tool_call_id);if(!a)continue;let s=n.name||a.name;if(this.excludeTools.has(s))continue;if(t[e]=new A({tool_call_id:n.tool_call_id,content:this.placeholder,name:n.name,artifact:void 0,response_metadata:{...n.response_metadata,context_editing:{cleared:!0,strategy:`clear_tool_uses`}}}),this.clearToolInputs){let e=t.indexOf(i);e>=0&&(t[e]=this.#i(i,n.tool_call_id))}let c=await r(t);u=Math.max(0,o-c)}if(this.clearAtLeast>0&&u<this.clearAtLeast){let e=c>0&&c<s.length?s.slice(-c):[];for(let n=e.length-1;n>=0&&!(u>=this.clearAtLeast);n--){let{idx:i,msg:a}=e[n];if(a.response_metadata?.context_editing?.cleared)continue;let s=this.#r(t.slice(0,i),a.tool_call_id);if(!s)continue;let c=s.tool_calls?.find(e=>e.id===a.tool_call_id);if(!c)continue;let l=a.name||c.name;if(this.excludeTools.has(l))continue;if(t[i]=new A({tool_call_id:a.tool_call_id,content:this.placeholder,name:a.name,artifact:void 0,response_metadata:{...a.response_metadata,context_editing:{cleared:!0,strategy:`clear_tool_uses`}}}),this.clearToolInputs){let e=t.indexOf(s);e>=0&&(t[e]=this.#i(s,a.tool_call_id))}let d=await r(t);u=Math.max(0,o-d)}}}#t(e,t,n){for(let r of this.#e){let i=!0,a=!1;if(r.messages!==void 0&&(a=!0,e.length<r.messages&&(i=!1)),r.tokens!==void 0&&(a=!0,t<r.tokens&&(i=!1)),r.fraction!==void 0){if(a=!0,!n)continue;let e=$f(n);if(typeof e==`number`){let n=Math.floor(e*r.fraction);if(n<=0)continue;t<n&&(i=!1)}else continue}if(a&&i)return!0}return!1}async#n(e,t,n){if(`messages`in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if(`tokens`in this.keep&&this.keep.tokens!==void 0){let n=this.keep.tokens,r=0,i=0;for(let a=e.length-1;a>=0;a--){let o=e[a],s=await t([o.msg]);if(r+s<=n)r+=s,i++;else break}return i}if(`fraction`in this.keep&&this.keep.fraction!==void 0){if(!n)return Qp;let r=$f(n);if(typeof r==`number`){let n=Math.floor(r*this.keep.fraction);if(n<=0)return Qp;let i=0,a=0;for(let r=e.length-1;r>=0;r--){let o=e[r],s=await t([o.msg]);if(i+s<=n)i+=s,a++;else break}return a}}return Qp}#r(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if(w.isInstance(r)&&r.tool_calls?.some(e=>e.id===t))return r}return null}#i(e,t){let n=e.tool_calls?.map(e=>e.id===t?{...e,args:{}}:e),r={...e.response_metadata},i={...r.context_editing},a=new Set(i.cleared_tool_inputs);return a.add(t),i.cleared_tool_inputs=Array.from(a).sort(),r.context_editing=i,new w({content:e.content,tool_calls:n,response_metadata:r,id:e.id,name:e.name,additional_kwargs:e.additional_kwargs})}};function em(e={}){let t=e.edits??[new $p],n=e.tokenCountMethod??`approx`;return Q({name:`ContextEditingMiddleware`,wrapModelCall:async(e,r)=>{if(!e.messages||e.messages.length===0)return r(e);let i=e.systemPrompt?[new D(e.systemPrompt)]:[],a=n===`approx`?Bd:async t=>{let n=[...i,...t];if(`getNumTokensFromMessages`in e.model)return e.model.getNumTokensFromMessages(n).then(({totalCount:e})=>e);throw Error(`Model "${e.model.getName()}" does not support token counting`)};for(let n of t)await n.apply({messages:e.messages,model:e.model,countTokens:a});return r(e)}})}function tm(e){return e?`Tool call limit exceeded. Do not call '${e}' again.`:`Tool call limit exceeded. Do not make additional tool calls.`}var nm=[`continue`,`error`,`end`],rm=`continue`;function im(e,t,n,r,i){let a=i?`'${i}' tool`:`Tool`,o=[];return n!==void 0&&e>n&&o.push(`thread limit exceeded (${e}/${n} calls)`),r!==void 0&&t>r&&o.push(`run limit exceeded (${t}/${r} calls)`),`${a} call limit reached: ${o.join(` and `)}.`}var am=ee(nm).default(rm),om=class extends Error{threadCount;runCount;threadLimit;runLimit;toolName;constructor(e,t,n,r,i=void 0){let a=im(e,t,n,r,i);super(a),this.name=`ToolCallLimitExceededError`,this.threadCount=e,this.runCount=t,this.threadLimit=n,this.runLimit=r,this.toolName=i}};T({toolName:k().optional(),threadLimit:C().optional(),runLimit:C().optional(),exitBehavior:am});var sm=T({threadToolCallCount:n(k(),C()).default({}),runToolCallCount:n(k(),C()).default({})}),cm=`__all__`;function lm(e){if(e.threadLimit===void 0&&e.runLimit===void 0)throw Error(`At least one limit must be specified (threadLimit or runLimit)`);let t=e.exitBehavior??rm,n=am.safeParse(t);if(!n.success)throw Error(wt(n.error).slice(2));if(e.threadLimit!==void 0&&e.runLimit!==void 0&&e.runLimit>e.threadLimit)throw Error(`runLimit (${e.runLimit}) cannot exceed threadLimit (${e.threadLimit}). The run limit should be less than or equal to the thread limit.`);return Q({name:e.toolName?`ToolCallLimitMiddleware[${e.toolName}]`:`ToolCallLimitMiddleware`,stateSchema:sm,afterModel:{canJumpTo:[`end`],hook:n=>{let r=[...n.messages].reverse().find(w.isInstance);if(!r||!r.tool_calls)return;let i=(t,n)=>e.threadLimit!==void 0&&t+1>e.threadLimit||e.runLimit!==void 0&&n+1>e.runLimit,a=t=>e.toolName===void 0||t.name===e.toolName,o=(e,t,n)=>{let r=[],o=[],s=t,c=n;for(let t of e)a(t)&&(i(s,c)?o.push(t):(r.push(t),s+=1,c+=1));return{allowed:r,blocked:o,finalThreadCount:s,finalRunCount:c+o.length}},s=e.toolName??cm,c={...n.threadToolCallCount??{}},l={...n.runToolCallCount??{}},u=c[s]??0,d=l[s]??0,{allowed:f,blocked:p,finalThreadCount:m,finalRunCount:h}=o(r.tool_calls,u,d);if(c[s]=m,l[s]=h,p.length===0)return f.length>0?{threadToolCallCount:c,runToolCallCount:l}:void 0;if(t===`error`)throw new om(m+p.length,h,e.threadLimit,e.runLimit,e.toolName);let g=tm(e.toolName),_=p.map(e=>new A({content:g,tool_call_id:e.id,name:e.name,status:`error`}));if(t===`end`){let t=[];if(e.toolName===void 0?new Set(r.tool_calls.map(e=>e.name).filter(Boolean)).size>1&&(t=f.length>0?f:r.tool_calls):t=r.tool_calls.filter(t=>t.name!==e.toolName),t.length>0){let e=Array.from(new Set(t.map(e=>e.name).filter(Boolean))).join(`, `);throw Error(`Cannot end execution with other tool calls pending. Found calls to: ${e}. Use 'continue' or 'error' behavior instead.`)}let n=im(m+p.length,h,e.threadLimit,e.runLimit,e.toolName);return _.push(new w(n)),{threadToolCallCount:c,runToolCallCount:l,jumpTo:`end`,messages:_}}return{threadToolCallCount:c,runToolCallCount:l,messages:_}}},afterAgent:()=>({runToolCallCount:{}})})}var um=`Use this tool to create and manage a structured task list for your current work session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
58
58
|
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
59
59
|
Only use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the taks directly.
|
|
@@ -278,14 +278,14 @@ Writing todos takes time and tokens, use it when it is helpful for managing comp
|
|
|
278
278
|
|
|
279
279
|
## Important To-Do List Usage Notes to Remember
|
|
280
280
|
- The \`write_todos\` tool should never be called multiple times in parallel.
|
|
281
|
-
- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`,fm=ee([`pending`,`in_progress`,`completed`]).describe(`Status of the todo`),pm=T({content:k().describe(`Content of the todo item`),status:fm}),mm=T({todos:ve(pm).default([])});function hm(e){let t=tn(({todos:e},t)=>new W({update:{todos:e,messages:[new A({content:`Updated todo list to ${JSON.stringify(e)}`,tool_call_id:t.toolCall?.id})]}}),{name:`write_todos`,description:e?.toolDescription??um,schema:T({todos:ve(pm).describe(`List of todo items to update`)})});return Q({name:`todoListMiddleware`,stateSchema:mm,tools:[t],wrapModelCall:(t,n)=>n({...t,systemMessage:t.systemMessage.concat(`\n\n${e?.systemPrompt??dm}`)}),afterModel:e=>{let n=e.messages;if(!n||n.length===0)return;let r=[...n].reverse().find(e=>w.isInstance(e));if(!r||!r.tool_calls||r.tool_calls.length===0)return;let i=r.tool_calls.filter(e=>e.name===t.name);if(i.length>1)return{messages:i.map(e=>new A({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:e.id,status:`error`}))}}})}var gm=`end`,_m=T({threadLimit:C().optional(),runLimit:C().optional(),exitBehavior:ee([`error`,`end`]).optional()}),vm=T({threadModelCallCount:C().default(0),runModelCallCount:C().default(0)}),ym=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:n,runCount:r}){let i=[];typeof e==`number`&&typeof n==`number`&&i.push(`thread level call limit reached with ${n} model calls`),typeof t==`number`&&typeof r==`number`&&i.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${i.length>0?`: ${i.join(`, `)}`:``}`),this.name=`ModelCallLimitMiddlewareError`}};function bm(e){return Q({name:`ModelCallLimitMiddleware`,contextSchema:_m,stateSchema:vm,beforeModel:{canJumpTo:[`end`],hook:(t,n)=>{let r=n.context.exitBehavior??e?.exitBehavior??gm;r===`throw`&&(console.warn(`The 'throw' exit behavior is deprecated. Please use 'error' instead.`),r=`error`);let i=n.context.threadLimit??e?.threadLimit,a=n.context.runLimit??e?.runLimit,o=t.threadModelCallCount,s=t.runModelCallCount;if(typeof i==`number`&&i<=o){let e=new ym({threadLimit:i,threadCount:o});if(r===`end`)return{jumpTo:`end`,messages:[new w(e.message)]};throw e}if(typeof a==`number`&&a<=s){let e=new ym({runLimit:a,runCount:s});if(r===`end`)return{jumpTo:`end`,messages:[new w(e.message)]};throw e}return t}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function xm(...e){return Q({name:`modelFallbackMiddleware`,wrapModelCall:async(t,n)=>{try{return await n(t)}catch(r){for(let r=0;r<e.length;r++)try{let i=e[r],a=typeof i==`string`?await In(i):i;return await n({...t,model:a})}catch(t){if(r===e.length-1)throw t}throw r}}})}var Sm=T({maxRetries:C().min(0).default(2),retryOn:st([
|
|
281
|
+
- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.`,fm=ee([`pending`,`in_progress`,`completed`]).describe(`Status of the todo`),pm=T({content:k().describe(`Content of the todo item`),status:fm}),mm=T({todos:ve(pm).default([])});function hm(e){let t=tn(({todos:e},t)=>new W({update:{todos:e,messages:[new A({content:`Updated todo list to ${JSON.stringify(e)}`,tool_call_id:t.toolCall?.id})]}}),{name:`write_todos`,description:e?.toolDescription??um,schema:T({todos:ve(pm).describe(`List of todo items to update`)})});return Q({name:`todoListMiddleware`,stateSchema:mm,tools:[t],wrapModelCall:(t,n)=>n({...t,systemMessage:t.systemMessage.concat(`\n\n${e?.systemPrompt??dm}`)}),afterModel:e=>{let n=e.messages;if(!n||n.length===0)return;let r=[...n].reverse().find(e=>w.isInstance(e));if(!r||!r.tool_calls||r.tool_calls.length===0)return;let i=r.tool_calls.filter(e=>e.name===t.name);if(i.length>1)return{messages:i.map(e=>new A({content:"Error: The `write_todos` tool should never be called multiple times in parallel. Please call it only once per model invocation to update the todo list.",tool_call_id:e.id,status:`error`}))}}})}var gm=`end`,_m=T({threadLimit:C().optional(),runLimit:C().optional(),exitBehavior:ee([`error`,`end`]).optional()}),vm=T({threadModelCallCount:C().default(0),runModelCallCount:C().default(0)}),ym=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:n,runCount:r}){let i=[];typeof e==`number`&&typeof n==`number`&&i.push(`thread level call limit reached with ${n} model calls`),typeof t==`number`&&typeof r==`number`&&i.push(`run level call limit reached with ${r} model calls`),super(`Model call limits exceeded${i.length>0?`: ${i.join(`, `)}`:``}`),this.name=`ModelCallLimitMiddlewareError`}};function bm(e){return Q({name:`ModelCallLimitMiddleware`,contextSchema:_m,stateSchema:vm,beforeModel:{canJumpTo:[`end`],hook:(t,n)=>{let r=n.context.exitBehavior??e?.exitBehavior??gm;r===`throw`&&(console.warn(`The 'throw' exit behavior is deprecated. Please use 'error' instead.`),r=`error`);let i=n.context.threadLimit??e?.threadLimit,a=n.context.runLimit??e?.runLimit,o=t.threadModelCallCount,s=t.runModelCallCount;if(typeof i==`number`&&i<=o){let e=new ym({threadLimit:i,threadCount:o});if(r===`end`)return{jumpTo:`end`,messages:[new w(e.message)]};throw e}if(typeof a==`number`&&a<=s){let e=new ym({runLimit:a,runCount:s});if(r===`end`)return{jumpTo:`end`,messages:[new w(e.message)]};throw e}return t}},afterModel:e=>({runModelCallCount:e.runModelCallCount+1,threadModelCallCount:e.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}function xm(...e){return Q({name:`modelFallbackMiddleware`,wrapModelCall:async(t,n)=>{try{return await n(t)}catch(r){for(let r=0;r<e.length;r++)try{let i=e[r],a=typeof i==`string`?await In(i):i;return await n({...t,model:a})}catch(t){if(r===e.length-1)throw t}throw r}}})}var Sm=T({maxRetries:C().min(0).default(2),retryOn:st([Qe().args(S(Error)).returns(xe()),ve(h())]).default(()=>()=>!0),backoffFactor:C().min(0).default(2),initialDelayMs:C().min(0).default(1e3),maxDelayMs:C().min(0).default(6e4),jitter:xe().default(!0)}),Cm=class extends Error{cause;constructor(e){let t=wt(e).slice(2);super(t),this.name=`InvalidRetryConfigError`,this.cause=e}},wm=T({onFailure:st([Ce(`error`),Ce(`continue`),Qe().args(S(Error)).returns(k())]).default(`continue`)}).merge(Sm);function Tm(e={}){let{success:t,error:n,data:r}=wm.safeParse(e);if(!t)throw new Cm(n);let{maxRetries:i,retryOn:a,onFailure:o,backoffFactor:s,initialDelayMs:c,maxDelayMs:l,jitter:u}=r,d=e=>typeof a==`function`?a(e):a.some(t=>e.constructor===t),f={backoffFactor:s,initialDelayMs:c,maxDelayMs:l,jitter:u},p=(e,t)=>{let n=e.constructor.name;return`Model call failed after ${t} ${t===1?`attempt`:`attempts`} with ${n}: ${e.message}`},m=(e,t)=>{if(o===`error`)throw e;let n;return n=typeof o==`function`?o(e):p(e,t),new w({content:n})};return Q({name:`modelRetryMiddleware`,contextSchema:wm,wrapModelCall:async(e,t)=>{for(let n=0;n<=i;n++)try{return await t(e)}catch(e){let t=n+1,r=e&&typeof e==`object`&&`message`in e?e:Error(String(e));if(!d(r))return m(r,t);if(n<i){let e=Wd(f,n);e>0&&await Ud(e)}else return m(r,t)}throw Error(`Unexpected: retry loop completed without returning`)}})}var Em=T({tools:ve(st([h(),h(),k()])).optional(),onFailure:st([Ce(`error`),Ce(`continue`),Ce(`raise`),Ce(`return_message`),Qe().args(S(Error)).returns(k())]).default(`continue`)}).merge(Sm);function Dm(e={}){let{success:t,error:n,data:r}=Em.safeParse(e);if(!t)throw new Cm(n);let{maxRetries:i,tools:a,retryOn:o,onFailure:s,backoffFactor:c,initialDelayMs:l,maxDelayMs:u,jitter:d}=r,f=s;s===`raise`?(console.warn("⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead."),f=`error`):s===`return_message`&&(console.warn("⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead."),f=`continue`);let p=[];for(let e of a??[])if(typeof e==`string`)p.push(e);else if(`name`in e&&typeof e.name==`string`)p.push(e.name);else throw TypeError(`Expected a tool name string or tool instance to be passed to toolRetryMiddleware`);let m=e=>p.length===0?!0:p.includes(e),h=e=>typeof o==`function`?o(e):o.some(t=>e instanceof t),g={backoffFactor:c,initialDelayMs:l,maxDelayMs:u,jitter:d},_=(e,t,n)=>{let r=t.constructor.name;return`Tool '${e}' failed after ${n} ${n===1?`attempt`:`attempts`} with ${r}`},v=(e,t,n,r)=>{if(f===`error`)throw n;let i;return i=typeof f==`function`?f(n):_(e,n,r),new A({content:i,tool_call_id:t,name:e,status:`error`})};return Q({name:`toolRetryMiddleware`,contextSchema:Em,wrapToolCall:async(e,t)=>{let n=e.tool?.name??e.toolCall.name;if(!m(n))return t(e);let r=e.toolCall.id??``;for(let a=0;a<=i;a++)try{return await t(e)}catch(e){let t=a+1,o=e&&typeof e==`object`&&`message`in e?e:Error(String(e));if(!h(o))return v(n,r,o,t);if(a<i){let e=Wd(g,a);e>0&&await Ud(e)}else return v(n,r,o,t)}throw Error(`Unexpected: retry loop completed without returning`)}})}function Om(e={}){let t,{tools:n,model:r}=e,i=!n||n.length===0,a=new Set;if(!i&&n)for(let e of n)if(typeof e==`string`)a.add(e);else{let t=typeof e.name==`string`?e.name:String(e.name);a.add(t)}let o,s=async()=>typeof r==`object`?r:typeof r==`string`?(o??=await In(r,{temperature:1}).catch(e=>(console.error(`Error initializing emulator model, using agent model:`,e),t)),o):t;return Q({name:`ToolEmulatorMiddleware`,wrapModelCall:async(e,n)=>(t=e.model,n(e)),wrapToolCall:async(e,t)=>{let n=e.toolCall.name;if(!(i||a.has(n)))return t(e);let r=e.toolCall.args,o=`You are emulating a tool call for testing purposes.
|
|
282
282
|
|
|
283
283
|
Tool: ${n}
|
|
284
284
|
Description: ${e.tool?.description||`No description available`}
|
|
285
285
|
Arguments: ${typeof r==`string`?r:JSON.stringify(r)}
|
|
286
286
|
|
|
287
287
|
Generate a realistic response that this tool would return given these arguments.
|
|
288
|
-
Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,c=await(await s()).invoke([new O(o)]);return new A({content:typeof c.content==`string`?c.content:JSON.stringify(c.content),tool_call_id:e.toolCall.id??``,name:n})}})}function km(e){return!e||typeof e!=`object`||!e||!(`client`in e)||!(`_getClientOptions`in e)||typeof e._getClientOptions!=`function`?!1:(e._getClientOptions(),typeof e.client==`object`&&e.client!==null&&`moderations`in e.client&&typeof e.client.moderations==`object`&&e.client.moderations!==null&&`create`in e.client.moderations&&typeof e.client.moderations.create==`function`)}var Am=`I'm sorry, but I can't comply with that request. It was flagged for {categories}.`,jm=class extends Error{content;stage;result;originalMessage;constructor({content:e,stage:t,result:n,message:r}){super(r),this.name=`OpenAIModerationError`,this.content=e,this.stage=t,this.result=n,this.originalMessage=r}};function Mm(e){let{model:t,moderationModel:n=`omni-moderation-latest`,checkInput:r=!0,checkOutput:i=!0,checkToolResults:a=!1,exitBehavior:o=`end`,violationMessage:s}=e,c,l=async()=>{if(c)return c;let e=typeof t==`string`?await In(t):t;if(!e.getName().includes(`ChatOpenAI`))throw Error(`Model must be an OpenAI model to use moderation middleware. Got: ${e.getName()}`);if(!km(e))throw Error(`Model must support moderation to use moderation middleware.`);return c=e,c},u=e=>e.content==null?null:e.text||null,d=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t.isInstance(e[n]))return n;return null},f=(e,t)=>{let n=[],r=t.categories;for(let[e,t]of Object.entries(r))t&&n.push(e.replace(/_/g,` `));let i=n.length>0?n.join(`, `):`OpenAI's safety policies`,a=s||Am,o=JSON.stringify(t.category_scores,null,2);try{return a.replace(`{categories}`,i).replace(`{category_scores}`,o).replace(`{original_content}`,e)}catch{return a}};function p(e,t){let n=c?._getClientOptions?.(),r={input:e,model:t?.model??`omni-moderation-latest`};return c.client.moderations.create(r,n)}let m=(e,t,n,r,i)=>{let a=f(r,i);if(o===`error`)throw new jm({content:r,stage:n,result:i,message:a});if(o===`end`)return{jumpTo:`end`,messages:[new w({content:a})]};if(t==null)return;let s=[...e],c=s[t],l=Object.getPrototypeOf(c).constructor;return s[t]=new l({...c,content:a}),{messages:s}},h=async e=>{let t=d(e,O);if(t==null)return null;let r=e[t],i=u(r);if(!i)return null;await l();let a=(await p(i,{model:n})).results.find(e=>e.flagged);return a?m(e,t,`input`,i,a):null},g=async e=>{let t=d(e,w);if(t==null)return null;let r=[...e],i=!1;for(let e=t+1;e<r.length;e++){let t=r[e];if(!A.isInstance(t))continue;let a=u(t);if(!a)continue;await l();let o=(await p(a,{model:n})).results.find(e=>e.flagged);if(!o)continue;let s=m(r,e,`tool`,a,o);if(s){if(`jumpTo`in s)return s;`messages`in s&&(r.splice(0,r.length,...s.messages),i=!0)}}return i?{messages:r}:null},_=async e=>{let t=d(e,w);if(t==null)return null;let r=e[t],i=u(r);if(!i)return null;await l();let a=(await p(i,{model:n})).results.find(e=>e.flagged);return a?m(e,t,`output`,i,a):null},v=async e=>{let t=[...e],n=!1;if(a){let e=await g(t);if(e){if(`jumpTo`in e)return e;`messages`in e&&(t.splice(0,t.length,...e.messages),n=!0)}}if(r){let e=await h(t);if(e){if(`jumpTo`in e)return e;`messages`in e&&(t.splice(0,t.length,...e.messages),n=!0)}}return n?{messages:t}:null};return Q({name:`OpenAIModerationMiddleware`,beforeModel:{hook:async e=>{if(!r&&!a)return;let t=e.messages||[];if(t.length!==0)return await v(t)??void 0},canJumpTo:[`end`]},afterModel:{hook:async e=>{if(!i)return;let t=e.messages||[];if(t.length!==0)return await _(t)??void 0},canJumpTo:[`end`]}})}var Nm=!0,Pm=`5m`,Fm=3,Im=`warn`,Lm=T({enableCaching:xe().optional(),ttl:ee([`5m`,`1h`]).optional(),minMessagesToCache:C().optional(),unsupportedModelBehavior:ee([`ignore`,`warn`,`raise`]).optional()}),Rm=class extends Error{constructor(e){super(e),this.name=`PromptCachingMiddlewareError`}};function zm(e){return Q({name:`PromptCachingMiddleware`,contextSchema:Lm,wrapModelCall:(t,n)=>{let r=t.runtime.context.enableCaching??e?.enableCaching??Nm,i=t.runtime.context.ttl??e?.ttl??Pm,a=t.runtime.context.minMessagesToCache??e?.minMessagesToCache??Fm,o=t.runtime.context.unsupportedModelBehavior??e?.unsupportedModelBehavior??Im;if(!r||!t.model)return n(t);if(!(t.model.getName()===`ChatAnthropic`||t.model.getName()===`ConfigurableModel`&&t.model._defaultConfig?.modelProvider===`anthropic`)){let e=t.model.getName(),r=`Unsupported model '${t.model.getName()===`ConfigurableModel`?`${e} (${t.model._defaultConfig?.modelProvider})`:e}'. Prompt caching requires an Anthropic model`;if(o===`raise`)throw new Rm(`${r} (e.g., 'anthropic:claude-4-0-sonnet').`);return o===`warn`&&console.warn(`PromptCachingMiddleware: Skipping caching for ${e}. Consider switching to an Anthropic model for caching benefits.`),n(t)}return t.state.messages.length+ +!!t.systemPrompt<a?n(t):n({...t,modelSettings:{...t.modelSettings,cache_control:{type:`ephemeral`,ttl:i}}})}})}kn({},{AIMessage:()=>w,AIMessageChunk:()=>we,BaseMessage:()=>gt,BaseMessageChunk:()=>pe,ClearToolUsesEdit:()=>$p,Document:()=>Br,DynamicStructuredTool:()=>sn,DynamicTool:()=>rn,FakeToolCallingModel:()=>Kd,HumanMessage:()=>O,HumanMessageChunk:()=>Ne,InMemoryStore:()=>Or,MIDDLEWARE_BRAND:()=>Gd,MiddlewareError:()=>Dd,MultipleStructuredOutputsError:()=>wd,MultipleToolsBoundError:()=>Cd,PIIDetectionError:()=>xp,ProviderStrategy:()=>Nd,StructuredOutputParsingError:()=>Td,StructuredTool:()=>on,SystemMessage:()=>D,SystemMessageChunk:()=>Ge,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>dm,Tool:()=>nn,ToolCallLimitExceededError:()=>om,ToolInvocationError:()=>Ed,ToolMessage:()=>A,ToolMessageChunk:()=>Te,ToolStrategy:()=>Md,anthropicPromptCachingMiddleware:()=>zm,applyStrategy:()=>zp,context:()=>Ja,contextEditingMiddleware:()=>em,countTokensApproximately:()=>Bd,createAgent:()=>Lf,createMiddleware:()=>Q,detectCreditCard:()=>Ap,detectEmail:()=>kp,detectIP:()=>jp,detectMacAddress:()=>Mp,detectUrl:()=>Np,dynamicSystemPromptMiddleware:()=>mp,filterMessages:()=>tt,humanInTheLoopMiddleware:()=>Hf,initChatModel:()=>In,llmToolSelectorMiddleware:()=>vp,modelCallLimitMiddleware:()=>bm,modelFallbackMiddleware:()=>xm,modelRetryMiddleware:()=>Tm,openAIModerationMiddleware:()=>Mm,piiMiddleware:()=>Hp,piiRedactionMiddleware:()=>Yp,providerStrategy:()=>Id,resolveRedactionRule:()=>Fp,summarizationMiddleware:()=>ep,todoListMiddleware:()=>hm,tool:()=>tn,toolCallLimitMiddleware:()=>lm,toolEmulatorMiddleware:()=>Om,toolRetryMiddleware:()=>Dm,toolStrategy:()=>Fd,trimMessages:()=>Ie});var Bm=class{static{e(this,`BaseAdapter`)}disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){let r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(t.debug(`No active sessions found, creating new ones...`),await e.createAllSessions());let i=e.getAllActiveSessions(),a=Object.values(i).map(e=>e.connector);return r.createToolsFromConnectors(a)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){let n=this.connectorToolMap.get(e);return t.debug(`Returning ${n.length} existing tools for connector`),n}let n=[];if(!await this.ensureConnectorInitialized(e))return[];for(let t of e.tools){let r=this.convertTool(t,e);r&&n.push(r)}return this.connectorToolMap.set(e,n),t.debug(`Loaded ${n.length} new tools for connector: ${n.map(e=>e?.name??String(e)).join(`, `)}`),n}async createToolsFromConnectors(e){let n=[];for(let t of e){let e=await this.loadToolsForConnector(t);n.push(...e)}return t.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){let n=[];if(!await this.ensureConnectorInitialized(e))return[];try{let r=(await e.listAllResources())?.resources||[];if(this.convertResource)for(let t of r){let r=this.convertResource(t,e);r&&n.push(r)}t.debug(`Loaded ${n.length} new resources for connector: ${n.map(e=>e?.name??String(e)).join(`, `)}`)}catch(e){t.warn(`Error loading resources for connector: ${e}`)}return n}async loadPromptsForConnector(e){let n=[];if(!await this.ensureConnectorInitialized(e))return[];try{let r=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(let t of r){let r=this.convertPrompt(t,e);r&&n.push(r)}t.debug(`Loaded ${n.length} new prompts for connector: ${n.map(e=>e?.name??String(e)).join(`, `)}`)}catch(e){t.warn(`Error loading prompts for connector: ${e}`)}return n}async createResourcesFromConnectors(e){let n=[];for(let t of e){let e=await this.loadResourcesForConnector(t);n.push(...e)}return t.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){let n=[];for(let t of e){let e=await this.loadPromptsForConnector(t);n.push(...e)}return t.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){t.debug(`Connector doesn't have tools, initializing it`);try{return await e.initialize(),!0}catch(e){return t.error(`Error initializing connector: ${e}`),!1}}return!0}};function Vm(e){try{return mn.convert(e)}catch(e){return t.warn(`Failed to convert JSON schema to Zod: ${e}`),Ot()}}e(Vm,`schemaToZod`);function Hm(e){return e.replace(/[^A-Za-z0-9_]+/g,`_`).toLowerCase().replace(/^_+|_+$/g,``)}e(Hm,`sanitizeToolName`);var Um=class extends Bm{static{e(this,`LangChainAdapter`)}usedToolNames=new Set;constructor(e=[]){super(e)}reserveName(e,t){if(!this.usedToolNames.has(e))return this.usedToolNames.add(e),e;if(t){let n=`${t}_${e}`;if(!this.usedToolNames.has(n))return this.usedToolNames.add(n),n;let r=2;for(;this.usedToolNames.has(`${n}_${r}`);)r++;let i=`${n}_${r}`;return this.usedToolNames.add(i),i}let n=2;for(;this.usedToolNames.has(`${e}_${n}`);)n++;let r=`${e}_${n}`;return this.usedToolNames.add(r),r}async createToolsFromConnectors(e){return this.usedToolNames.clear(),super.createToolsFromConnectors(e)}convertTool(n,r){if(this.disallowedTools.includes(n.name))return null;let i=n.inputSchema?Vm(n.inputSchema):M({}).optional();return new sn({name:this.reserveName(n.name??`NO NAME`),description:n.description??``,schema:i,func:e(async e=>{t.debug(`MCP tool "${n.name}" received input: ${JSON.stringify(e)}`);try{let t=await r.callTool(n.name,e);return JSON.stringify(t)}catch(e){return t.error(`Error executing MCP tool: ${e.message}`),`Error executing MCP tool: ${String(e)}`}},`func`)})}convertResource(n,r){let i=Hm(n.name||n.uri)||`resource`,a=this.reserveName(i,`resource`),o=n.uri;return new sn({name:a,description:n.description||`Return the content of the resource located at URI ${o}.`,schema:M({}).optional(),func:e(async()=>{t.debug(`Resource tool: "${a}" called`);try{let e=await r.readResource(o);return e.contents&&e.contents.length>0?e.contents.map(e=>typeof e==`string`?e:e.text?e.text:e.uri?e.uri:JSON.stringify(e)).join(`
|
|
288
|
+
Return ONLY the tool's output, no explanation or preamble. Introduce variation into your responses.`,c=await(await s()).invoke([new O(o)]);return new A({content:typeof c.content==`string`?c.content:JSON.stringify(c.content),tool_call_id:e.toolCall.id??``,name:n})}})}function km(e){return!e||typeof e!=`object`||!e||!(`client`in e)||!(`_getClientOptions`in e)||typeof e._getClientOptions!=`function`?!1:(e._getClientOptions(),typeof e.client==`object`&&e.client!==null&&`moderations`in e.client&&typeof e.client.moderations==`object`&&e.client.moderations!==null&&`create`in e.client.moderations&&typeof e.client.moderations.create==`function`)}var Am=`I'm sorry, but I can't comply with that request. It was flagged for {categories}.`,jm=class extends Error{content;stage;result;originalMessage;constructor({content:e,stage:t,result:n,message:r}){super(r),this.name=`OpenAIModerationError`,this.content=e,this.stage=t,this.result=n,this.originalMessage=r}};function Mm(e){let{model:t,moderationModel:n=`omni-moderation-latest`,checkInput:r=!0,checkOutput:i=!0,checkToolResults:a=!1,exitBehavior:o=`end`,violationMessage:s}=e,c,l=async()=>{if(c)return c;let e=typeof t==`string`?await In(t):t;if(!e.getName().includes(`ChatOpenAI`))throw Error(`Model must be an OpenAI model to use moderation middleware. Got: ${e.getName()}`);if(!km(e))throw Error(`Model must support moderation to use moderation middleware.`);return c=e,c},u=e=>e.content==null?null:e.text||null,d=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t.isInstance(e[n]))return n;return null},f=(e,t)=>{let n=[],r=t.categories;for(let[e,t]of Object.entries(r))t&&n.push(e.replace(/_/g,` `));let i=n.length>0?n.join(`, `):`OpenAI's safety policies`,a=s||Am,o=JSON.stringify(t.category_scores,null,2);try{return a.replace(`{categories}`,i).replace(`{category_scores}`,o).replace(`{original_content}`,e)}catch{return a}};function p(e,t){let n=c?._getClientOptions?.(),r={input:e,model:t?.model??`omni-moderation-latest`};return c.client.moderations.create(r,n)}let m=(e,t,n,r,i)=>{let a=f(r,i);if(o===`error`)throw new jm({content:r,stage:n,result:i,message:a});if(o===`end`)return{jumpTo:`end`,messages:[new w({content:a})]};if(t==null)return;let s=[...e],c=s[t],l=Object.getPrototypeOf(c).constructor;return s[t]=new l({...c,content:a}),{messages:s}},h=async e=>{let t=d(e,O);if(t==null)return null;let r=e[t],i=u(r);if(!i)return null;await l();let a=(await p(i,{model:n})).results.find(e=>e.flagged);return a?m(e,t,`input`,i,a):null},g=async e=>{let t=d(e,w);if(t==null)return null;let r=[...e],i=!1;for(let e=t+1;e<r.length;e++){let t=r[e];if(!A.isInstance(t))continue;let a=u(t);if(!a)continue;await l();let o=(await p(a,{model:n})).results.find(e=>e.flagged);if(!o)continue;let s=m(r,e,`tool`,a,o);if(s){if(`jumpTo`in s)return s;`messages`in s&&(r.splice(0,r.length,...s.messages),i=!0)}}return i?{messages:r}:null},_=async e=>{let t=d(e,w);if(t==null)return null;let r=e[t],i=u(r);if(!i)return null;await l();let a=(await p(i,{model:n})).results.find(e=>e.flagged);return a?m(e,t,`output`,i,a):null},v=async e=>{let t=[...e],n=!1;if(a){let e=await g(t);if(e){if(`jumpTo`in e)return e;`messages`in e&&(t.splice(0,t.length,...e.messages),n=!0)}}if(r){let e=await h(t);if(e){if(`jumpTo`in e)return e;`messages`in e&&(t.splice(0,t.length,...e.messages),n=!0)}}return n?{messages:t}:null};return Q({name:`OpenAIModerationMiddleware`,beforeModel:{hook:async e=>{if(!r&&!a)return;let t=e.messages||[];if(t.length!==0)return await v(t)??void 0},canJumpTo:[`end`]},afterModel:{hook:async e=>{if(!i)return;let t=e.messages||[];if(t.length!==0)return await _(t)??void 0},canJumpTo:[`end`]}})}var Nm=!0,Pm=`5m`,Fm=3,Im=`warn`,Lm=T({enableCaching:xe().optional(),ttl:ee([`5m`,`1h`]).optional(),minMessagesToCache:C().optional(),unsupportedModelBehavior:ee([`ignore`,`warn`,`raise`]).optional()}),Rm=class extends Error{constructor(e){super(e),this.name=`PromptCachingMiddlewareError`}};function zm(e){return Q({name:`PromptCachingMiddleware`,contextSchema:Lm,wrapModelCall:(t,n)=>{let r=t.runtime.context.enableCaching??e?.enableCaching??Nm,i=t.runtime.context.ttl??e?.ttl??Pm,a=t.runtime.context.minMessagesToCache??e?.minMessagesToCache??Fm,o=t.runtime.context.unsupportedModelBehavior??e?.unsupportedModelBehavior??Im;if(!r||!t.model)return n(t);if(!(t.model.getName()===`ChatAnthropic`||t.model.getName()===`ConfigurableModel`&&t.model._defaultConfig?.modelProvider===`anthropic`)){let e=t.model.getName(),r=`Unsupported model '${t.model.getName()===`ConfigurableModel`?`${e} (${t.model._defaultConfig?.modelProvider})`:e}'. Prompt caching requires an Anthropic model`;if(o===`raise`)throw new Rm(`${r} (e.g., 'anthropic:claude-4-0-sonnet').`);return o===`warn`&&console.warn(`PromptCachingMiddleware: Skipping caching for ${e}. Consider switching to an Anthropic model for caching benefits.`),n(t)}return t.state.messages.length+ +!!t.systemPrompt<a?n(t):n({...t,modelSettings:{...t.modelSettings,cache_control:{type:`ephemeral`,ttl:i}}})}})}kn({},{AIMessage:()=>w,AIMessageChunk:()=>we,BaseMessage:()=>gt,BaseMessageChunk:()=>pe,ClearToolUsesEdit:()=>$p,Document:()=>Br,DynamicStructuredTool:()=>sn,DynamicTool:()=>rn,FakeToolCallingModel:()=>Kd,HumanMessage:()=>O,HumanMessageChunk:()=>Ne,InMemoryStore:()=>Or,MIDDLEWARE_BRAND:()=>Gd,MiddlewareError:()=>Dd,MultipleStructuredOutputsError:()=>wd,MultipleToolsBoundError:()=>Cd,PIIDetectionError:()=>xp,ProviderStrategy:()=>Nd,StructuredOutputParsingError:()=>Td,StructuredTool:()=>on,SystemMessage:()=>D,SystemMessageChunk:()=>Ge,TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT:()=>dm,Tool:()=>nn,ToolCallLimitExceededError:()=>om,ToolInvocationError:()=>Ed,ToolMessage:()=>A,ToolMessageChunk:()=>Te,ToolStrategy:()=>Md,anthropicPromptCachingMiddleware:()=>zm,applyStrategy:()=>zp,context:()=>Ja,contextEditingMiddleware:()=>em,countTokensApproximately:()=>Bd,createAgent:()=>Lf,createMiddleware:()=>Q,detectCreditCard:()=>Ap,detectEmail:()=>kp,detectIP:()=>jp,detectMacAddress:()=>Mp,detectUrl:()=>Np,dynamicSystemPromptMiddleware:()=>mp,filterMessages:()=>et,humanInTheLoopMiddleware:()=>Hf,initChatModel:()=>In,llmToolSelectorMiddleware:()=>vp,modelCallLimitMiddleware:()=>bm,modelFallbackMiddleware:()=>xm,modelRetryMiddleware:()=>Tm,openAIModerationMiddleware:()=>Mm,piiMiddleware:()=>Hp,piiRedactionMiddleware:()=>Yp,providerStrategy:()=>Id,resolveRedactionRule:()=>Fp,summarizationMiddleware:()=>ep,todoListMiddleware:()=>hm,tool:()=>tn,toolCallLimitMiddleware:()=>lm,toolEmulatorMiddleware:()=>Om,toolRetryMiddleware:()=>Dm,toolStrategy:()=>Fd,trimMessages:()=>Ie});var Bm=class{static{e(this,`BaseAdapter`)}disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,n){let r=new this(n);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(t.debug(`No active sessions found, creating new ones...`),await e.createAllSessions());let i=e.getAllActiveSessions(),a=Object.values(i).map(e=>e.connector);return r.createToolsFromConnectors(a)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){let n=this.connectorToolMap.get(e);return t.debug(`Returning ${n.length} existing tools for connector`),n}let n=[];if(!await this.ensureConnectorInitialized(e))return[];for(let t of e.tools){let r=this.convertTool(t,e);r&&n.push(r)}return this.connectorToolMap.set(e,n),t.debug(`Loaded ${n.length} new tools for connector: ${n.map(e=>e?.name??String(e)).join(`, `)}`),n}async createToolsFromConnectors(e){let n=[];for(let t of e){let e=await this.loadToolsForConnector(t);n.push(...e)}return t.debug(`Available tools: ${n.length}`),n}async loadResourcesForConnector(e){let n=[];if(!await this.ensureConnectorInitialized(e))return[];try{let r=(await e.listAllResources())?.resources||[];if(this.convertResource)for(let t of r){let r=this.convertResource(t,e);r&&n.push(r)}t.debug(`Loaded ${n.length} new resources for connector: ${n.map(e=>e?.name??String(e)).join(`, `)}`)}catch(e){t.warn(`Error loading resources for connector: ${e}`)}return n}async loadPromptsForConnector(e){let n=[];if(!await this.ensureConnectorInitialized(e))return[];try{let r=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(let t of r){let r=this.convertPrompt(t,e);r&&n.push(r)}t.debug(`Loaded ${n.length} new prompts for connector: ${n.map(e=>e?.name??String(e)).join(`, `)}`)}catch(e){t.warn(`Error loading prompts for connector: ${e}`)}return n}async createResourcesFromConnectors(e){let n=[];for(let t of e){let e=await this.loadResourcesForConnector(t);n.push(...e)}return t.debug(`Available resources: ${n.length}`),n}async createPromptsFromConnectors(e){let n=[];for(let t of e){let e=await this.loadPromptsForConnector(t);n.push(...e)}return t.debug(`Available prompts: ${n.length}`),n}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){t.debug(`Connector doesn't have tools, initializing it`);try{return await e.initialize(),!0}catch(e){return t.error(`Error initializing connector: ${e}`),!1}}return!0}};function Vm(e){try{return mn.convert(e)}catch(e){return t.warn(`Failed to convert JSON schema to Zod: ${e}`),Ot()}}e(Vm,`schemaToZod`);function Hm(e){return e.replace(/[^A-Za-z0-9_]+/g,`_`).toLowerCase().replace(/^_+|_+$/g,``)}e(Hm,`sanitizeToolName`);var Um=class extends Bm{static{e(this,`LangChainAdapter`)}usedToolNames=new Set;constructor(e=[]){super(e)}reserveName(e,t){if(!this.usedToolNames.has(e))return this.usedToolNames.add(e),e;if(t){let n=`${t}_${e}`;if(!this.usedToolNames.has(n))return this.usedToolNames.add(n),n;let r=2;for(;this.usedToolNames.has(`${n}_${r}`);)r++;let i=`${n}_${r}`;return this.usedToolNames.add(i),i}let n=2;for(;this.usedToolNames.has(`${e}_${n}`);)n++;let r=`${e}_${n}`;return this.usedToolNames.add(r),r}async createToolsFromConnectors(e){return this.usedToolNames.clear(),super.createToolsFromConnectors(e)}convertTool(n,r){if(this.disallowedTools.includes(n.name))return null;let i=n.inputSchema?Vm(n.inputSchema):M({}).optional();return new sn({name:this.reserveName(n.name??`NO NAME`),description:n.description??``,schema:i,func:e(async e=>{t.debug(`MCP tool "${n.name}" received input: ${JSON.stringify(e)}`);try{let t=await r.callTool(n.name,e);return JSON.stringify(t)}catch(e){return t.error(`Error executing MCP tool: ${e.message}`),`Error executing MCP tool: ${String(e)}`}},`func`)})}convertResource(n,r){let i=Hm(n.name||n.uri)||`resource`,a=this.reserveName(i,`resource`),o=n.uri;return new sn({name:a,description:n.description||`Return the content of the resource located at URI ${o}.`,schema:M({}).optional(),func:e(async()=>{t.debug(`Resource tool: "${a}" called`);try{let e=await r.readResource(o);return e.contents&&e.contents.length>0?e.contents.map(e=>typeof e==`string`?e:e.text?e.text:e.uri?e.uri:JSON.stringify(e)).join(`
|
|
289
289
|
`):`Resource is empty or unavailable`}catch(e){return t.error(`Error reading resource: ${e.message}`),`Error reading resource: ${String(e)}`}},`func`)})}convertPrompt(n,r){let i=M({}).optional();if(n.arguments&&n.arguments.length>0){let e={};for(let t of n.arguments){let n=jt();t.required===!1?e[t.name]=n.optional():e[t.name]=n}i=Object.keys(e).length>0?M(e):M({}).optional()}let a=Hm(n.name||`prompt`)||`prompt`;return new sn({name:this.reserveName(a,`prompt`),description:n.description||``,schema:i,func:e(async e=>{t.debug(`Prompt tool: "${n.name}" called with args: ${JSON.stringify(e)}`);try{let t=await r.getPrompt(n.name,e);return t.messages&&t.messages.length>0?t.messages.map(e=>typeof e==`string`?e:e.content?typeof e.content==`string`?e.content:JSON.stringify(e.content):JSON.stringify(e)).join(`
|
|
290
290
|
`):`Prompt returned no messages`}catch(e){return t.error(`Error getting prompt: ${e.message}`),`Error getting prompt: ${String(e)}`}},`func`)})}},Wm=class extends on{static{e(this,`MCPServerTool`)}name=`mcp_server_tool`;description=`Base tool for MCP server operations.`;schema;_manager;constructor(e){super(),this._manager=e}async _call(e,t,n){throw Error(`Method not implemented.`)}get manager(){return this._manager}},Gm=M({}),Km=class extends Wm{static{e(this,`AcquireActiveMCPServerTool`)}name=`get_active_mcp_server`;description=`Get the currently active MCP (Model Context Protocol) server`;schema=Gm;constructor(e){super(e)}async _call(){return this.manager.activeServer?`Currently active MCP server: ${this.manager.activeServer}`:`No MCP server is currently active. Use connect_to_mcp_server to connect to a server.`}},qm=class extends on{static{e(this,`AddMCPServerFromConfigTool`)}name=`add_mcp_server_from_config`;description=`Adds a new MCP server to the client from a configuration object and connects to it, making its tools available.`;schema=M({serverName:jt().describe(`The name for the new MCP server.`),serverConfig:Ot().describe(`The configuration object for the server. This should not include the top-level "mcpServers" key.`)});manager;constructor(e){super(),this.manager=e}async _call({serverName:e,serverConfig:n}){try{this.manager.client.addServer(e,n);let r=`Server '${e}' added to the client.`;t.debug(`Connecting to new server '${e}' and discovering tools.`);let i=(await this.manager.client.createSession(e)).connector,a=await this.manager.adapter.createToolsFromConnectors([i]);this.manager.serverTools[e]=a,this.manager.initializedServers[e]=!0,this.manager.activeServer=e;let o=a.length;return r+=` Session created and connected. '${e}' is now the active server with ${o} tools available.`,r+=`
|
|
291
291
|
|
|
@@ -340,7 +340,7 @@ Here are the tools *currently* available to you (this list includes server manag
|
|
|
340
340
|
\u2022 Missing or invalid MCP server configurations
|
|
341
341
|
\u2022 Network connectivity issues with MCP servers
|
|
342
342
|
\u2022 Missing environment variables or credentials
|
|
343
|
-
Raw error: ${c}`)}return l?this.parseStructuredResponse(c,l):typeof c==`object`&&c&&`result`in c?c.result:typeof c==`string`?c:String(c)}catch(e){throw e instanceof Error?e.name===`AbortError`?(t.error(`\u274C Remote execution timed out: ${e}`),Error(`Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${e.message}`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${String(e)}`))}}async*stream(e,t,n,r,i){return await this.run(e,t,n,r,i)}async close(){t.debug(`🔌 Remote agent client closed`)}},fh={openai:{package:`@langchain/openai`,className:`ChatOpenAI`,envVars:[`OPENAI_API_KEY`],defaultModel:`gpt-4o`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`,envVars:[`ANTHROPIC_API_KEY`],defaultModel:`claude-sonnet-4-6`},google:{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`,envVars:[`GOOGLE_API_KEY`,`GOOGLE_GENERATIVE_AI_API_KEY`],defaultModel:`gemini-pro`},groq:{package:`@langchain/groq`,className:`ChatGroq`,envVars:[`GROQ_API_KEY`],defaultModel:`llama-3.1-70b-versatile`}};function ph(e){let t=e.split(`/`);if(t.length!==2)throw Error(`Invalid LLM string format. Expected 'provider/model', got '${e}'. Examples: 'openai/gpt-4', 'anthropic/claude-sonnet-4-6', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);let[n,r]=t;if(!n||!r)throw Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${e}'`);let i=n.toLowerCase();if(!(i in fh)){let e=Object.keys(fh).join(`, `);throw Error(`Unsupported LLM provider '${n}'. Supported providers: ${e}`)}return{provider:i,model:r}}e(ph,`parseLLMString`);function mh(e,n){if(n?.apiKey)return n.apiKey;let r=fh[e];if(typeof process<`u`)for(let n of r.envVars){let r={}[n];if(r)return t.debug(`Using API key from environment variable ${n} for provider ${e}`),r}let i=r.envVars.join(` or `);throw Error(`API key not found for provider '${e}'. Set ${i} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${e}/model', llmConfig: { apiKey: 'your-key' } })`)}e(mh,`getAPIKey`);async function hh(e,n){t.debug(`Creating LLM from string: ${e}`);let{provider:r,model:i}=ph(e),a=fh[r],o=mh(r,n),s;try{t.debug(`Importing package ${a.package}...`),s=await Mt(()=>import(a.package),[])}catch(e){throw e?.code===`MODULE_NOT_FOUND`||e?.message?.includes(`Cannot find module`)||e?.message?.includes(`Cannot find package`)?Error(`Package '${a.package}' is not installed. Install it with: npm install ${a.package} or yarn add ${a.package}`):Error(`Failed to import ${a.package}: ${e?.message||e}`)}let c=s[a.className];if(!c)throw Error(`Could not find ${a.className} in package ${a.package}. This might be a version compatibility issue.`);let l={model:i,apiKey:o,...n};n?.apiKey&&(delete l.apiKey,l.apiKey=o),(r===`anthropic`||r===`google`||r===`openai`||r===`groq`)&&(l.model=i);try{let e=new c(l);return t.debug(`Successfully created ${r} LLM with model ${i}`),e}catch(e){throw Error(`Failed to instantiate ${a.className} with model '${i}': ${e?.message||e}`)}}e(hh,`createLLMFromString`);function gh(e){try{return ph(e),!0}catch{return!1}}e(gh,`isValidLLMString`);function _h(){return Object.keys(fh)}e(_h,`getSupportedProviders`);function vh(e,t,n,r,i,a){if(typeof e==`object`&&e){let t=e;return{query:t.prompt,maxSteps:t.maxSteps,manageConnector:t.manageConnector,externalHistory:t.externalHistory,outputSchema:t.schema,signal:t.signal}}return{query:e,maxSteps:t,manageConnector:n,externalHistory:r,outputSchema:i,signal:a}}e(vh,`normalizeRunOptions`);var yh=class{static{e(this,`MCPAgent`)}static getPackageVersion(){return Et()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;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;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(n){if(n.agentId){this.isRemote=!0,this.remoteAgent=new dh({agentId:n.agentId,apiKey:n.apiKey,baseUrl:n.baseUrl}),this.maxSteps=n.maxSteps??5,this.memoryEnabled=n.memoryEnabled??!0,this.autoInitialize=n.autoInitialize??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Um,this.telemetry=Tt.getInstance(),this.modelProvider=`remote`,this.modelName=`remote-agent`,this.observabilityManager=new nh({customCallbacks:n.callbacks,agentId:n.agentId}),this.callbacks=[];return}if(!n.llm)throw Error(`llm is required for local execution. For remote execution, provide agentId instead.`);if(typeof n.llm==`string`){if(this.isSimplifiedMode=!0,this.llmString=n.llm,this.llmConfig=n.llmConfig,this.mcpServersConfig=n.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw Error(`Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }`);this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],t.debug(`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=n.llm,this.client=n.client,this.connectors=n.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw Error(`Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.`);if(this.maxSteps=n.maxSteps??5,this.autoInitialize=n.autoInitialize??!1,this.memoryEnabled=n.memoryEnabled??!0,this.systemPrompt=n.systemPrompt??null,this.systemPromptTemplateOverride=n.systemPromptTemplate??null,this.additionalInstructions=n.additionalInstructions??null,this.disallowedTools=n.disallowedTools??[],this.additionalTools=n.additionalTools??[],this.toolsUsedNames=n.toolsUsedNames??[],this.exposeResourcesAsTools=n.exposeResourcesAsTools??!0,this.exposePromptsAsTools=n.exposePromptsAsTools??!0,this.useServerManager=n.useServerManager??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.isSimplifiedMode)this.adapter=n.adapter??new Um(this.disallowedTools),this.telemetry=Tt.getInstance(),this.modelProvider=`unknown`,this.modelName=`unknown`;else{if(this.useServerManager){if(!this.client)throw Error(`'client' must be provided when 'useServerManager' is true.`);this.adapter=n.adapter??new Um(this.disallowedTools),this.serverManager=n.serverManagerFactory?.(this.client)??new th(this.client,this.adapter)}else this.adapter=n.adapter??new Um(this.disallowedTools);if(this.telemetry=Tt.getInstance(),this.llm){let[e,t]=Dt(this.llm);this.modelProvider=e,this.modelName=t}else this.modelProvider=`unknown`,this.modelName=`unknown`}this.observabilityManager=new nh({customCallbacks:n.callbacks,verbose:this.verbose,observe:this.observe,agentId:n.agentId,metadataProvider:e(()=>this.getMetadata(),`metadataProvider`),tagsProvider:e(()=>this.getTags(),`tagsProvider`)}),Object.defineProperty(this,`agentExecutor`,{get:e(()=>this._agentExecutor,`get`),configurable:!0}),Object.defineProperty(this,`tools`,{get:e(()=>this._tools,`get`),configurable:!0}),Object.defineProperty(this,`initialized`,{get:e(()=>this._initialized,`get`),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(t.debug(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.debug(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.debug(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await Mt(async()=>{let{MCPClient:e}=await import(`./client-LWDVEFBW-BaSj9Sdi.js`);return{MCPClient:e}},__vite__mapDeps([6,5,7,3,8,9,2,1,10,11,12]));this.client=new e({mcpServers:this.mcpServersConfig}),t.debug(`✅ MCPClient created successfully`)}if(this.llmString){t.debug(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.debug(`✅ LLM created successfully`);let[e,n]=Dt(this.llm);this.modelProvider=e,this.modelName=n}catch(e){throw Error(`Failed to create LLM from string '${this.llmString}': ${e?.message||e}`)}}if(this.useServerManager){if(!this.client)throw Error(`'client' must be available when 'useServerManager' is true.`);this.serverManager=new th(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();let e=await this.observabilityManager.getHandlerNames();if(e.length>0&&t.debug(`\u{1F4CA} Observability enabled with: ${e.join(`, `)}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();let e=this.serverManager.tools;this._tools=e,this._tools.push(...this.additionalTools),t.debug(`\u{1F527} Server manager mode active with ${e.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),t.debug(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.debug(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.debug(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){let e=this.sessions.code_mode;if(e)this._tools=await this.adapter.createToolsFromConnectors([e.connector]),t.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} code mode tools`);else throw Error(`Code mode enabled but code_mode session not found`)}else{let e=Object.values(this.sessions).map(e=>e.connector),n=await this.adapter.createToolsFromConnectors(e),r=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(e):[],i=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(e):[];this._tools=[...n,...r,...i],t.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${n.length} tools, ${r.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{t.debug(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);for(let e of this.connectors)e.isClientConnected||await e.connect();let e=await this.adapter.createToolsFromConnectors(this.connectors),n=await this.adapter.createResourcesFromConnectors(this.connectors),r=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...e,...n,...r],this._tools.push(...this.additionalTools),t.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.debug(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;let n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),t.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),t.debug(`✨ Agent initialization complete`)}async createSystemMessageFromTools(e){this.systemMessage=ah(e,this.systemPromptTemplateOverride??oh,sh,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(e=>!(e instanceof D))])}createAgent(){if(!this.llm)throw Error(`LLM is required to create agent`);let e=this.systemMessage?.content??`You are a helpful assistant.`,n=this._tools.map(e=>e.name);t.debug(`\u{1F9E0} Agent ready with tools: ${n.join(`, `)}`);let r=[bm({runLimit:this.maxSteps})],i=Lf({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return t.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}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 D(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof D)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),t.debug(`Agent recreated with new system message`))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Um(this.disallowedTools),this._initialized&&t.debug(`Agent already initialized. Changes will take effect on next initialization.`)}getDisallowedTools(){return this.disallowedTools}setMetadata(e){let n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},t.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){let n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],t.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){let n={};for(let[r,i]of Object.entries(e)){if(typeof r!=`string`||r.length===0){t.warn(`Invalid metadata key: ${r}. Skipping.`);continue}let e=r.replace(/[^\w-]/g,`_`);if(i==null)n[e]=i;else if(typeof i==`string`||typeof i==`number`||typeof i==`boolean`)n[e]=i;else if(Array.isArray(i)){let t=i.filter(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`);t.length>0&&(n[e]=t)}else if(typeof i==`object`)try{let r=JSON.stringify(i);r.length>1e3?(t.warn(`Metadata value for key '${e}' is too large. Truncating.`),n[e]=`${r.substring(0,1e3)}...`):n[e]=i}catch(n){t.warn(`Failed to serialize metadata value for key '${e}': ${n}. Skipping.`)}else t.warn(`Unsupported metadata value type for key '${e}': ${typeof i}. Skipping.`)}return n}sanitizeTags(e){return e.filter(e=>typeof e==`string`&&e.length>0).map(e=>e.replace(/[^\w:-]/g,`_`)).filter(e=>e.length<=50)}getMCPServerInfo(){let e={};try{if(this.client){let n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;let r={};for(let e of n)try{let t=this.client.getServerConfig(e);if(t){let n=`unknown`;t.command?n=`command`:t.url?n=`http`:t.ws_url&&(n=`websocket`),r[e]={type:n,has_args:!!t.args,has_env:!!t.env,has_headers:!!t.headers,url:t.url||null,command:t.command||null}}}catch(n){t.warn(`Failed to get config for server '${e}': ${n}`),r[e]={type:`error`,error:`config_unavailable`}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(e=>e.publicIdentifier),e.mcp_server_types=this.connectors.map(e=>e.constructor.name))}catch(n){t.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)){let t=[];for(let n of e)if(typeof n==`object`&&n)`text`in n&&typeof n.text==`string`?t.push(n.text):`content`in n?t.push(this._normalizeOutput(n.content)):t.push(String(n));else{let e=n&&typeof n==`object`&&`text`in n?n.text:null;if(typeof e==`string`)t.push(e);else{let e=n&&typeof n==`object`&&`content`in n?n.content:n;t.push(this._normalizeOutput(e))}}return t.join(``)}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof w)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`ai`||e===`assistant`)return!0}catch{}if(typeof t._getType==`function`)try{let e=t._getType();if(e===`ai`||e===`assistant`)return!0}catch{}return`type`in t?t.type===`ai`||t.type===`assistant`:`role`in t?t.role===`ai`||t.role===`assistant`:!1}_messageHasToolCalls(e){return typeof e==`object`&&e&&`tool_calls`in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof O)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`human`||e===`user`)return!0}catch{}return`type`in t&&(t.type===`human`||t.type===`user`)||`role`in t&&(t.role===`human`||t.role===`user`)}_isToolMessageLike(e){if(e instanceof A)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{if(t.getType()===`tool`)return!0}catch{}return`type`in t&&t.type===`tool`}_getMessageContent(e){if(e instanceof w||e&&typeof e==`object`&&`content`in e)return e.content}async _consumeAndReturn(e){for(;;){let{done:t,value:n}=await e.next();if(t)return n}}async run(e,t,n,r,i,a){let{query:o,maxSteps:s,manageConnector:c,externalHistory:l,outputSchema:u,signal:d}=vh(e,t,n,r,i,a);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(o,s,c,l,u);let f=this.stream(o,s,c,l,u,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,i,a,o){let{query:s,maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:d,signal:f}=vh(e,n,r,i,a,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(s,c,l,u,d);let p=!1,m=Date.now(),h=!1,g=null,_=0;try{if((l&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),p=!0),!this._agentExecutor)throw Error(`MCP agent failed to initialize`);if(this.useServerManager&&this.serverManager){let e=this.serverManager.tools,n=new Set(e.map(e=>e.name)),r=new Set(this._tools.map(e=>e.name));(n.size!==r.size||[...n].some(e=>!r.has(e)))&&(t.debug(`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...n].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}let e=u??this.conversationHistory,n=[];for(let t of e)(this._isHumanMessageLike(t)||this._isAIMessageLike(t)||this._isToolMessageLike(t))&&n.push(t);let r=s.length>50?`${s.slice(0,50).replace(/\n/g,` `)}...`:s.replace(/\n/g,` `);t.debug(`\u{1F4AC} Received query: '${r}'`),t.debug(`🏁 Starting agent execution`);let i=0,a=[...n,new O(s)];for(;i<=3;){let e={messages:a},n=!1,r=await this._agentExecutor.stream(e,{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},...f&&{signal:f}});for await(let e of r){if(f?.aborted)break;for(let[r,o]of Object.entries(e))if(t.debug(`\u{1F4E6} Node '${r}' output: ${JSON.stringify(o)}`),o&&typeof o==`object`&&`messages`in o){let e=o.messages;Array.isArray(e)||(e=[e]);for(let t of e)a.includes(t)||a.push(t);for(let r of e){if(`tool_calls`in r&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0)for(let e of r.tool_calls){let n=e.name||`unknown`,r=e.args||{};this.toolsUsedNames.push(n),_++;let i=JSON.stringify(r);i.length>100&&(i=`${i.slice(0,97)}...`),t.debug(`\u{1F527} Tool call: ${n} with input: ${i}`),yield{action:{tool:n,toolInput:r,log:`Calling tool ${n}`},observation:``}}if(this._isToolMessageLike(r)){let e=r.content,a=String(e);if(a.length>100&&(a=`${a.slice(0,97)}...`),a=a.replace(/\n/g,` `),t.debug(`\u{1F4C4} Tool result: ${a}`),this.useServerManager&&this.serverManager){let e=this.serverManager.tools,r=new Set(e.map(e=>e.name)),a=new Set(this._tools.map(e=>e.name));if(r.size!==a.size||[...r].some(e=>!a.has(e))){t.debug(`\u{1F504} Tools changed during execution. New tools: ${[...r].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),n=!0,i++,t.debug(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.debug(`✅ Agent finished with output`))}if(n)break}if(n)break}if(!n)break;if(i>3){t.warn(`⚠️ Max restarts (3) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){let e=a.slice(n.length);for(let t of e)this.addToHistory(t)}if(d&&g)try{t.debug(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new w(`Structured result: ${JSON.stringify(e)}`)),t.debug(`✅ Structured output successful`),h=!0,e}catch(e){throw t.error(`\u274C Structured output failed: ${e}`),Error(`Failed to generate structured output: ${e instanceof Error?e.message:String(e)}`)}return t.debug(`\u{1F389} Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),h=!0,g||`No output generated`}catch(e){throw t.error(`\u274C Error running query: ${e}`),p&&l&&(t.debug(`🧹 Cleaning up resources after error`),await this.close()),e}finally{let e=Date.now()-m,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0,i=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:`stream`,query:s,success:h,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:i.length,toolsAvailableNames:i.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,stepsTaken:_,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||``,executionTimeMs:e,errorType:h?null:`execution_error`,conversationHistoryLength:r}),l&&!this.client&&p&&(t.debug(`🧹 Closing agent after stream completion`),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(t.debug(`Flushing observability traces...`),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}t.debug(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.debug(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.debug(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.debug(`🔄 Disconnecting connector`),await e.disconnect();this.isSimplifiedMode&&this.llm&&(t.debug(`🔄 Clearing LLM reference (simplified mode)`),this.llm=void 0),`connectorToolMap`in this.adapter&&(this.adapter=new Um)}finally{this._initialized=!1,t.debug(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await Mt(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-B8BJrcag.js`);return{prettyStreamEvents:e}},__vite__mapDeps([13,3,5,2]));for await(let o of a(this.streamEvents(e,t,n,r,i)))yield;return``}async*streamEvents(e,n,r=!0,i,a,o){let s=vh(e,n,r,i,a,o),{query:c}=s,{maxSteps:l,manageConnector:u,externalHistory:d,outputSchema:f,signal:p}=s,m=!1,h=Date.now(),g=!1,_=0,v=0,y=``;f&&(c=this._enhanceQueryWithSchema(c,f));try{(u&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),m=!0);let e=this._agentExecutor;if(!e)throw Error(`MCP agent failed to initialize`);this.maxSteps=l??this.maxSteps;let n=typeof c==`string`&&c.length>50?`${c.slice(0,50).replace(/\n/g,` `)}...`:typeof c==`string`?c.replace(/\n/g,` `):String(c);t.debug(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.debug(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new O({content:c})));let r=d??this.conversationHistory,i=[];for(let e of r)this._isHumanMessageLike(e)||this._isAIMessageLike(e)||this._isToolMessageLike(e)?i.push(e):t.debug(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new O(c)];t.debug(`callbacks`,this.callbacks);let o=e.streamEvents({messages:a},{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},...p&&{signal:p}});for await(let e of o){if(p?.aborted)break;if(_++,!(!e||typeof e!=`object`)){if(e.event===`on_chat_model_stream`&&e.data?.chunk?.content&&(v+=e.data.chunk.content.length),e.event===`on_chat_model_stream`&&e.data?.chunk){let n=e.data.chunk;if(n.content){y||=``;let e=this._normalizeOutput(n.content);y+=e,t.debug(`\u{1F4DD} Accumulated response length: ${y.length}`)}}if(yield e,e.event===`on_chain_end`&&e.data?.output&&!y){let t=e.data.output;Array.isArray(t)&&t.length>0&&t[0]?.text?y=t[0].text:typeof t==`string`?y=t:t&&typeof t==`object`&&`output`in t&&(y=t.output)}}}if(f&&y){t.debug(`🔧 Attempting structured output conversion...`);try{let e=!1,n=null,r=null;this._attemptStructuredOutput(y,this.llm,f).then(t=>(e=!0,n=t,t)).catch(t=>{throw e=!0,r=t,t});let i=0;for(;!e;)await new Promise(e=>setTimeout(e,2e3)),e||(i++,yield{event:`on_structured_output_progress`,data:{message:`Converting to structured output... (${i*2}s)`,elapsed:i*2}});if(r)throw r;n&&(yield{event:`on_structured_output`,data:{output:n}},this.memoryEnabled&&this.addToHistory(new w(`Structured result: ${JSON.stringify(n)}`)),t.debug(`✅ Structured output successful`))}catch(e){t.warn(`\u26A0\uFE0F Structured output failed: ${e}`),yield{event:`on_structured_output_error`,data:{error:e instanceof Error?e.message:String(e)}}}}else this.memoryEnabled&&y&&this.addToHistory(new w(y));console.log(`
|
|
343
|
+
Raw error: ${c}`)}return l?this.parseStructuredResponse(c,l):typeof c==`object`&&c&&`result`in c?c.result:typeof c==`string`?c:String(c)}catch(e){throw e instanceof Error?e.name===`AbortError`?(t.error(`\u274C Remote execution timed out: ${e}`),Error(`Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${e.message}`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${String(e)}`))}}async*stream(e,t,n,r,i){return await this.run(e,t,n,r,i)}async close(){t.debug(`🔌 Remote agent client closed`)}},fh={openai:{package:`@langchain/openai`,className:`ChatOpenAI`,envVars:[`OPENAI_API_KEY`],defaultModel:`gpt-4o`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`,envVars:[`ANTHROPIC_API_KEY`],defaultModel:`claude-sonnet-4-6`},google:{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`,envVars:[`GOOGLE_API_KEY`,`GOOGLE_GENERATIVE_AI_API_KEY`],defaultModel:`gemini-pro`},groq:{package:`@langchain/groq`,className:`ChatGroq`,envVars:[`GROQ_API_KEY`],defaultModel:`llama-3.1-70b-versatile`}};function ph(e){let t=e.split(`/`);if(t.length!==2)throw Error(`Invalid LLM string format. Expected 'provider/model', got '${e}'. Examples: 'openai/gpt-4', 'anthropic/claude-sonnet-4-6', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);let[n,r]=t;if(!n||!r)throw Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${e}'`);let i=n.toLowerCase();if(!(i in fh)){let e=Object.keys(fh).join(`, `);throw Error(`Unsupported LLM provider '${n}'. Supported providers: ${e}`)}return{provider:i,model:r}}e(ph,`parseLLMString`);function mh(e,n){if(n?.apiKey)return n.apiKey;let r=fh[e];if(typeof process<`u`)for(let n of r.envVars){let r={}[n];if(r)return t.debug(`Using API key from environment variable ${n} for provider ${e}`),r}let i=r.envVars.join(` or `);throw Error(`API key not found for provider '${e}'. Set ${i} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${e}/model', llmConfig: { apiKey: 'your-key' } })`)}e(mh,`getAPIKey`);async function hh(e,n){t.debug(`Creating LLM from string: ${e}`);let{provider:r,model:i}=ph(e),a=fh[r],o=mh(r,n),s;try{t.debug(`Importing package ${a.package}...`),s=await Mt(()=>import(a.package),[])}catch(e){throw e?.code===`MODULE_NOT_FOUND`||e?.message?.includes(`Cannot find module`)||e?.message?.includes(`Cannot find package`)?Error(`Package '${a.package}' is not installed. Install it with: npm install ${a.package} or yarn add ${a.package}`):Error(`Failed to import ${a.package}: ${e?.message||e}`)}let c=s[a.className];if(!c)throw Error(`Could not find ${a.className} in package ${a.package}. This might be a version compatibility issue.`);let l={model:i,apiKey:o,...n};n?.apiKey&&(delete l.apiKey,l.apiKey=o),(r===`anthropic`||r===`google`||r===`openai`||r===`groq`)&&(l.model=i);try{let e=new c(l);return t.debug(`Successfully created ${r} LLM with model ${i}`),e}catch(e){throw Error(`Failed to instantiate ${a.className} with model '${i}': ${e?.message||e}`)}}e(hh,`createLLMFromString`);function gh(e){try{return ph(e),!0}catch{return!1}}e(gh,`isValidLLMString`);function _h(){return Object.keys(fh)}e(_h,`getSupportedProviders`);function vh(e,t,n,r,i,a){if(typeof e==`object`&&e){let t=e;return{query:t.prompt,maxSteps:t.maxSteps,manageConnector:t.manageConnector,externalHistory:t.externalHistory,outputSchema:t.schema,signal:t.signal}}return{query:e,maxSteps:t,manageConnector:n,externalHistory:r,outputSchema:i,signal:a}}e(vh,`normalizeRunOptions`);var yh=class{static{e(this,`MCPAgent`)}static getPackageVersion(){return Et()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;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;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(n){if(n.agentId){this.isRemote=!0,this.remoteAgent=new dh({agentId:n.agentId,apiKey:n.apiKey,baseUrl:n.baseUrl}),this.maxSteps=n.maxSteps??5,this.memoryEnabled=n.memoryEnabled??!0,this.autoInitialize=n.autoInitialize??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Um,this.telemetry=Tt.getInstance(),this.modelProvider=`remote`,this.modelName=`remote-agent`,this.observabilityManager=new nh({customCallbacks:n.callbacks,agentId:n.agentId}),this.callbacks=[];return}if(!n.llm)throw Error(`llm is required for local execution. For remote execution, provide agentId instead.`);if(typeof n.llm==`string`){if(this.isSimplifiedMode=!0,this.llmString=n.llm,this.llmConfig=n.llmConfig,this.mcpServersConfig=n.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw Error(`Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }`);this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],t.debug(`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=n.llm,this.client=n.client,this.connectors=n.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw Error(`Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.`);if(this.maxSteps=n.maxSteps??5,this.autoInitialize=n.autoInitialize??!1,this.memoryEnabled=n.memoryEnabled??!0,this.systemPrompt=n.systemPrompt??null,this.systemPromptTemplateOverride=n.systemPromptTemplate??null,this.additionalInstructions=n.additionalInstructions??null,this.disallowedTools=n.disallowedTools??[],this.additionalTools=n.additionalTools??[],this.toolsUsedNames=n.toolsUsedNames??[],this.exposeResourcesAsTools=n.exposeResourcesAsTools??!0,this.exposePromptsAsTools=n.exposePromptsAsTools??!0,this.useServerManager=n.useServerManager??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.isSimplifiedMode)this.adapter=n.adapter??new Um(this.disallowedTools),this.telemetry=Tt.getInstance(),this.modelProvider=`unknown`,this.modelName=`unknown`;else{if(this.useServerManager){if(!this.client)throw Error(`'client' must be provided when 'useServerManager' is true.`);this.adapter=n.adapter??new Um(this.disallowedTools),this.serverManager=n.serverManagerFactory?.(this.client)??new th(this.client,this.adapter)}else this.adapter=n.adapter??new Um(this.disallowedTools);if(this.telemetry=Tt.getInstance(),this.llm){let[e,t]=Dt(this.llm);this.modelProvider=e,this.modelName=t}else this.modelProvider=`unknown`,this.modelName=`unknown`}this.observabilityManager=new nh({customCallbacks:n.callbacks,verbose:this.verbose,observe:this.observe,agentId:n.agentId,metadataProvider:e(()=>this.getMetadata(),`metadataProvider`),tagsProvider:e(()=>this.getTags(),`tagsProvider`)}),Object.defineProperty(this,`agentExecutor`,{get:e(()=>this._agentExecutor,`get`),configurable:!0}),Object.defineProperty(this,`tools`,{get:e(()=>this._tools,`get`),configurable:!0}),Object.defineProperty(this,`initialized`,{get:e(()=>this._initialized,`get`),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(t.debug(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.debug(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.debug(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await Mt(async()=>{let{MCPClient:e}=await import(`./client-W7K33MEL-CSZOULYm.js`);return{MCPClient:e}},__vite__mapDeps([6,5,7,3,8,9,2,1,10,11,12]));this.client=new e({mcpServers:this.mcpServersConfig}),t.debug(`✅ MCPClient created successfully`)}if(this.llmString){t.debug(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.debug(`✅ LLM created successfully`);let[e,n]=Dt(this.llm);this.modelProvider=e,this.modelName=n}catch(e){throw Error(`Failed to create LLM from string '${this.llmString}': ${e?.message||e}`)}}if(this.useServerManager){if(!this.client)throw Error(`'client' must be available when 'useServerManager' is true.`);this.serverManager=new th(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();let e=await this.observabilityManager.getHandlerNames();if(e.length>0&&t.debug(`\u{1F4CA} Observability enabled with: ${e.join(`, `)}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();let e=this.serverManager.tools;this._tools=e,this._tools.push(...this.additionalTools),t.debug(`\u{1F527} Server manager mode active with ${e.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),t.debug(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.debug(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.debug(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){let e=this.sessions.code_mode;if(e)this._tools=await this.adapter.createToolsFromConnectors([e.connector]),t.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} code mode tools`);else throw Error(`Code mode enabled but code_mode session not found`)}else{let e=Object.values(this.sessions).map(e=>e.connector),n=await this.adapter.createToolsFromConnectors(e),r=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(e):[],i=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(e):[];this._tools=[...n,...r,...i],t.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${n.length} tools, ${r.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{t.debug(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);for(let e of this.connectors)e.isClientConnected||await e.connect();let e=await this.adapter.createToolsFromConnectors(this.connectors),n=await this.adapter.createResourcesFromConnectors(this.connectors),r=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...e,...n,...r],this._tools.push(...this.additionalTools),t.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.debug(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;let n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),t.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),t.debug(`✨ Agent initialization complete`)}async createSystemMessageFromTools(e){this.systemMessage=ah(e,this.systemPromptTemplateOverride??oh,sh,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(e=>!(e instanceof D))])}createAgent(){if(!this.llm)throw Error(`LLM is required to create agent`);let e=this.systemMessage?.content??`You are a helpful assistant.`,n=this._tools.map(e=>e.name);t.debug(`\u{1F9E0} Agent ready with tools: ${n.join(`, `)}`);let r=[bm({runLimit:this.maxSteps})],i=Lf({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return t.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}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 D(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof D)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),t.debug(`Agent recreated with new system message`))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Um(this.disallowedTools),this._initialized&&t.debug(`Agent already initialized. Changes will take effect on next initialization.`)}getDisallowedTools(){return this.disallowedTools}setMetadata(e){let n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},t.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){let n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],t.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){let n={};for(let[r,i]of Object.entries(e)){if(typeof r!=`string`||r.length===0){t.warn(`Invalid metadata key: ${r}. Skipping.`);continue}let e=r.replace(/[^\w-]/g,`_`);if(i==null)n[e]=i;else if(typeof i==`string`||typeof i==`number`||typeof i==`boolean`)n[e]=i;else if(Array.isArray(i)){let t=i.filter(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`);t.length>0&&(n[e]=t)}else if(typeof i==`object`)try{let r=JSON.stringify(i);r.length>1e3?(t.warn(`Metadata value for key '${e}' is too large. Truncating.`),n[e]=`${r.substring(0,1e3)}...`):n[e]=i}catch(n){t.warn(`Failed to serialize metadata value for key '${e}': ${n}. Skipping.`)}else t.warn(`Unsupported metadata value type for key '${e}': ${typeof i}. Skipping.`)}return n}sanitizeTags(e){return e.filter(e=>typeof e==`string`&&e.length>0).map(e=>e.replace(/[^\w:-]/g,`_`)).filter(e=>e.length<=50)}getMCPServerInfo(){let e={};try{if(this.client){let n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;let r={};for(let e of n)try{let t=this.client.getServerConfig(e);if(t){let n=`unknown`;t.command?n=`command`:t.url?n=`http`:t.ws_url&&(n=`websocket`),r[e]={type:n,has_args:!!t.args,has_env:!!t.env,has_headers:!!t.headers,url:t.url||null,command:t.command||null}}}catch(n){t.warn(`Failed to get config for server '${e}': ${n}`),r[e]={type:`error`,error:`config_unavailable`}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(e=>e.publicIdentifier),e.mcp_server_types=this.connectors.map(e=>e.constructor.name))}catch(n){t.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)){let t=[];for(let n of e)if(typeof n==`object`&&n)`text`in n&&typeof n.text==`string`?t.push(n.text):`content`in n?t.push(this._normalizeOutput(n.content)):t.push(String(n));else{let e=n&&typeof n==`object`&&`text`in n?n.text:null;if(typeof e==`string`)t.push(e);else{let e=n&&typeof n==`object`&&`content`in n?n.content:n;t.push(this._normalizeOutput(e))}}return t.join(``)}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof w)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`ai`||e===`assistant`)return!0}catch{}if(typeof t._getType==`function`)try{let e=t._getType();if(e===`ai`||e===`assistant`)return!0}catch{}return`type`in t?t.type===`ai`||t.type===`assistant`:`role`in t?t.role===`ai`||t.role===`assistant`:!1}_messageHasToolCalls(e){return typeof e==`object`&&e&&`tool_calls`in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof O)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`human`||e===`user`)return!0}catch{}return`type`in t&&(t.type===`human`||t.type===`user`)||`role`in t&&(t.role===`human`||t.role===`user`)}_isToolMessageLike(e){if(e instanceof A)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{if(t.getType()===`tool`)return!0}catch{}return`type`in t&&t.type===`tool`}_getMessageContent(e){if(e instanceof w||e&&typeof e==`object`&&`content`in e)return e.content}async _consumeAndReturn(e){for(;;){let{done:t,value:n}=await e.next();if(t)return n}}async run(e,t,n,r,i,a){let{query:o,maxSteps:s,manageConnector:c,externalHistory:l,outputSchema:u,signal:d}=vh(e,t,n,r,i,a);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(o,s,c,l,u);let f=this.stream(o,s,c,l,u,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,i,a,o){let{query:s,maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:d,signal:f}=vh(e,n,r,i,a,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(s,c,l,u,d);let p=!1,m=Date.now(),h=!1,g=null,_=0;try{if((l&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),p=!0),!this._agentExecutor)throw Error(`MCP agent failed to initialize`);if(this.useServerManager&&this.serverManager){let e=this.serverManager.tools,n=new Set(e.map(e=>e.name)),r=new Set(this._tools.map(e=>e.name));(n.size!==r.size||[...n].some(e=>!r.has(e)))&&(t.debug(`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...n].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}let e=u??this.conversationHistory,n=[];for(let t of e)(this._isHumanMessageLike(t)||this._isAIMessageLike(t)||this._isToolMessageLike(t))&&n.push(t);let r=s.length>50?`${s.slice(0,50).replace(/\n/g,` `)}...`:s.replace(/\n/g,` `);t.debug(`\u{1F4AC} Received query: '${r}'`),t.debug(`🏁 Starting agent execution`);let i=0,a=[...n,new O(s)];for(;i<=3;){let e={messages:a},n=!1,r=await this._agentExecutor.stream(e,{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},...f&&{signal:f}});for await(let e of r){if(f?.aborted)break;for(let[r,o]of Object.entries(e))if(t.debug(`\u{1F4E6} Node '${r}' output: ${JSON.stringify(o)}`),o&&typeof o==`object`&&`messages`in o){let e=o.messages;Array.isArray(e)||(e=[e]);for(let t of e)a.includes(t)||a.push(t);for(let r of e){if(`tool_calls`in r&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0)for(let e of r.tool_calls){let n=e.name||`unknown`,r=e.args||{};this.toolsUsedNames.push(n),_++;let i=JSON.stringify(r);i.length>100&&(i=`${i.slice(0,97)}...`),t.debug(`\u{1F527} Tool call: ${n} with input: ${i}`),yield{action:{tool:n,toolInput:r,log:`Calling tool ${n}`},observation:``}}if(this._isToolMessageLike(r)){let e=r.content,a=String(e);if(a.length>100&&(a=`${a.slice(0,97)}...`),a=a.replace(/\n/g,` `),t.debug(`\u{1F4C4} Tool result: ${a}`),this.useServerManager&&this.serverManager){let e=this.serverManager.tools,r=new Set(e.map(e=>e.name)),a=new Set(this._tools.map(e=>e.name));if(r.size!==a.size||[...r].some(e=>!a.has(e))){t.debug(`\u{1F504} Tools changed during execution. New tools: ${[...r].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),n=!0,i++,t.debug(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.debug(`✅ Agent finished with output`))}if(n)break}if(n)break}if(!n)break;if(i>3){t.warn(`⚠️ Max restarts (3) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){let e=a.slice(n.length);for(let t of e)this.addToHistory(t)}if(d&&g)try{t.debug(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new w(`Structured result: ${JSON.stringify(e)}`)),t.debug(`✅ Structured output successful`),h=!0,e}catch(e){throw t.error(`\u274C Structured output failed: ${e}`),Error(`Failed to generate structured output: ${e instanceof Error?e.message:String(e)}`)}return t.debug(`\u{1F389} Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),h=!0,g||`No output generated`}catch(e){throw t.error(`\u274C Error running query: ${e}`),p&&l&&(t.debug(`🧹 Cleaning up resources after error`),await this.close()),e}finally{let e=Date.now()-m,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0,i=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:`stream`,query:s,success:h,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:i.length,toolsAvailableNames:i.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,stepsTaken:_,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||``,executionTimeMs:e,errorType:h?null:`execution_error`,conversationHistoryLength:r}),l&&!this.client&&p&&(t.debug(`🧹 Closing agent after stream completion`),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(t.debug(`Flushing observability traces...`),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}t.debug(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.debug(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.debug(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.debug(`🔄 Disconnecting connector`),await e.disconnect();this.isSimplifiedMode&&this.llm&&(t.debug(`🔄 Clearing LLM reference (simplified mode)`),this.llm=void 0),`connectorToolMap`in this.adapter&&(this.adapter=new Um)}finally{this._initialized=!1,t.debug(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await Mt(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-B8BJrcag.js`);return{prettyStreamEvents:e}},__vite__mapDeps([13,3,5,2]));for await(let o of a(this.streamEvents(e,t,n,r,i)))yield;return``}async*streamEvents(e,n,r=!0,i,a,o){let s=vh(e,n,r,i,a,o),{query:c}=s,{maxSteps:l,manageConnector:u,externalHistory:d,outputSchema:f,signal:p}=s,m=!1,h=Date.now(),g=!1,_=0,v=0,y=``;f&&(c=this._enhanceQueryWithSchema(c,f));try{(u&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),m=!0);let e=this._agentExecutor;if(!e)throw Error(`MCP agent failed to initialize`);this.maxSteps=l??this.maxSteps;let n=typeof c==`string`&&c.length>50?`${c.slice(0,50).replace(/\n/g,` `)}...`:typeof c==`string`?c.replace(/\n/g,` `):String(c);t.debug(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.debug(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new O({content:c})));let r=d??this.conversationHistory,i=[];for(let e of r)this._isHumanMessageLike(e)||this._isAIMessageLike(e)||this._isToolMessageLike(e)?i.push(e):t.debug(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new O(c)];t.debug(`callbacks`,this.callbacks);let o=e.streamEvents({messages:a},{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},...p&&{signal:p}});for await(let e of o){if(p?.aborted)break;if(_++,!(!e||typeof e!=`object`)){if(e.event===`on_chat_model_stream`&&e.data?.chunk?.content&&(v+=e.data.chunk.content.length),e.event===`on_chat_model_stream`&&e.data?.chunk){let n=e.data.chunk;if(n.content){y||=``;let e=this._normalizeOutput(n.content);y+=e,t.debug(`\u{1F4DD} Accumulated response length: ${y.length}`)}}if(yield e,e.event===`on_chain_end`&&e.data?.output&&!y){let t=e.data.output;Array.isArray(t)&&t.length>0&&t[0]?.text?y=t[0].text:typeof t==`string`?y=t:t&&typeof t==`object`&&`output`in t&&(y=t.output)}}}if(f&&y){t.debug(`🔧 Attempting structured output conversion...`);try{let e=!1,n=null,r=null;this._attemptStructuredOutput(y,this.llm,f).then(t=>(e=!0,n=t,t)).catch(t=>{throw e=!0,r=t,t});let i=0;for(;!e;)await new Promise(e=>setTimeout(e,2e3)),e||(i++,yield{event:`on_structured_output_progress`,data:{message:`Converting to structured output... (${i*2}s)`,elapsed:i*2}});if(r)throw r;n&&(yield{event:`on_structured_output`,data:{output:n}},this.memoryEnabled&&this.addToHistory(new w(`Structured result: ${JSON.stringify(n)}`)),t.debug(`✅ Structured output successful`))}catch(e){t.warn(`\u26A0\uFE0F Structured output failed: ${e}`),yield{event:`on_structured_output_error`,data:{error:e instanceof Error?e.message:String(e)}}}}else this.memoryEnabled&&y&&this.addToHistory(new w(y));console.log(`
|
|
344
344
|
|
|
345
345
|
`),t.debug(`\u{1F389} StreamEvents complete - ${_} events emitted`),g=!0}catch(e){throw t.error(`\u274C Error during streamEvents: ${e}`),m&&u&&(t.debug(`🧹 Cleaning up resources after initialization error in streamEvents`),await this.close()),e}finally{let e=Date.now()-h,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:`streamEvents`,query:c,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:u??!0,externalHistoryUsed:d!==void 0,response:`[STREAMED RESPONSE - ${v} chars]`,executionTimeMs:e,errorType:g?null:`streaming_error`,conversationHistoryLength:r}),u&&!this.client&&m&&(t.debug(`🧹 Closing agent after streamEvents completion`),await this.close())}}async _attemptStructuredOutput(e,n,r){t.debug(`\u{1F504} Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),t.debug(`\u{1F504} Raw result: ${JSON.stringify(e,null,2)}`);let i=null,a=``;if(t.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify(Ct(r),null,2)}`),n&&`withStructuredOutput`in n&&typeof n.withStructuredOutput==`function`)i=n.withStructuredOutput(r);else if(n)i=n;else throw Error(`LLM is required for structured output`);let{$schema:o,additionalProperties:s,...c}=Ct(r);a=JSON.stringify(c,null,2),t.debug(`\u{1F504} Schema description: ${a}`);let l=``;typeof e==`string`?l=e:e&&typeof e==`object`&&(l=JSON.stringify(e)),t.debug(`rawResult`,e),l||=JSON.stringify(e);let u=``;for(let e=1;e<=3;e++){t.debug(`\u{1F504} Structured output attempt ${e}/3`);let n=`
|
|
346
346
|
Please format the following information according to the EXACT schema specified below.
|