@arcgis/ai-components 5.2.0-next.72 → 5.2.0-next.74
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/agent-utils/LLMAgent.d.ts +5 -2
- package/dist/agent-utils/LLMAgent.js +1 -1
- package/dist/agentic-workflow/jsonTypes.d.ts +8 -1
- package/dist/agentic-workflow/nodes/AgentNode.d.ts +2 -0
- package/dist/agentic-workflow/nodes/tools/ArcgisTool.d.ts +21 -0
- package/dist/cdn/253R5CBD.js +2 -0
- package/dist/cdn/2VBPA27M.js +18 -0
- package/dist/cdn/{DWYODVWW.js → 323DHVYA.js} +5 -5
- package/dist/cdn/34O57OGV.js +2 -0
- package/dist/cdn/{FSMHR7GK.js → 4HDDRBIY.js} +1 -1
- package/dist/cdn/4MFEKBKL.js +11 -0
- package/dist/cdn/{Y5UFOH54.js → 4NJ2FF7H.js} +1 -1
- package/dist/cdn/4YXYLX4H.js +2 -0
- package/dist/cdn/5DVRVY4L.js +2 -0
- package/dist/cdn/5PJXNTLZ.js +2 -0
- package/dist/cdn/5R6QUF5B.js +2 -0
- package/dist/cdn/5RVELJU4.js +36 -0
- package/dist/cdn/5WLNL4HZ.js +2 -0
- package/dist/cdn/66SKMECC.js +2 -0
- package/dist/cdn/6CLF7KIK.js +2 -0
- package/dist/cdn/{S6ZAQRC6.js → 6KFMRBAA.js} +1 -1
- package/dist/cdn/77QFSIWW.js +5 -0
- package/dist/cdn/7E2QMWK6.js +2 -0
- package/dist/cdn/{HO2YDJI2.js → 7M6VKBTK.js} +1 -1
- package/dist/cdn/{HJG7QM2R.js → 7VAQUCBU.js} +1 -1
- package/dist/cdn/ACJTJLZN.js +2 -0
- package/dist/cdn/AI6DYOKR.js +181 -0
- package/dist/cdn/AT4XVTJR.js +44 -0
- package/dist/cdn/BS2PFNU4.js +2 -0
- package/dist/cdn/CCC6LBMY.js +2 -0
- package/dist/cdn/CGXQAB3A.js +2 -0
- package/dist/cdn/{M3MRIGDZ.js → CP5BVGJU.js} +1 -1
- package/dist/cdn/CWD37QFT.js +2 -0
- package/dist/cdn/DY36ATOA.js +2 -0
- package/dist/cdn/DYASSC7Z.js +2 -0
- package/dist/cdn/EAEQONP7.js +2 -0
- package/dist/cdn/EMLOVMD4.js +2 -0
- package/dist/cdn/EWLXNGKH.js +208 -0
- package/dist/cdn/FAR3DFFK.js +2 -0
- package/dist/cdn/FDOMMK2M.js +2 -0
- package/dist/cdn/GRHIFCQX.js +2 -0
- package/dist/cdn/{S3XUYAUX.js → HHFNQR6Z.js} +1 -1
- package/dist/cdn/{WQKNV6KK.js → HMUWQCXU.js} +1 -1
- package/dist/cdn/HZ5ARNAM.js +2 -0
- package/dist/cdn/I6PD2HSL.js +2 -0
- package/dist/cdn/IDUC4CPV.js +2 -0
- package/dist/cdn/IRNSIUBT.js +2 -0
- package/dist/cdn/{OYNIFMCJ.js → J6SZIQJA.js} +1 -1
- package/dist/cdn/K335IAIE.js +2 -0
- package/dist/cdn/K33MZ726.js +2 -0
- package/dist/cdn/KA3FF3ZO.js +2 -0
- package/dist/cdn/{DBHLKLKM.js → KPO4XX6J.js} +1 -1
- package/dist/cdn/{I4L45WQS.js → L7XTRDFM.js} +1 -1
- package/dist/cdn/LCFIADOZ.js +2 -0
- package/dist/cdn/MDM2K3U7.js +2 -0
- package/dist/cdn/MM33KJPF.js +2 -0
- package/dist/cdn/NIY32GK2.js +2 -0
- package/dist/cdn/{3ZPPYCNL.js → ONMNQBPO.js} +1 -1
- package/dist/cdn/ONQ6JSBJ.js +2 -0
- package/dist/cdn/{6QJFOL6M.js → OWTGH34K.js} +1 -1
- package/dist/cdn/{XPTCV6YV.js → PSYRZMX2.js} +1 -1
- package/dist/cdn/Q4IQUEZN.js +14 -0
- package/dist/cdn/QNNGPA3Q.js +2 -0
- package/dist/cdn/QRHZXLZN.js +2 -0
- package/dist/cdn/QVOMX3R6.js +2 -0
- package/dist/cdn/QZ3NQTNQ.js +2 -0
- package/dist/cdn/RADWN4ZP.js +2 -0
- package/dist/cdn/RU2T7GUX.js +2 -0
- package/dist/cdn/S6OYR4VI.js +156 -0
- package/dist/cdn/T2GJLEYV.js +2 -0
- package/dist/cdn/TKYI5QRL.js +2 -0
- package/dist/cdn/{5SFZS2RD.js → TQXLSW4A.js} +2 -2
- package/dist/cdn/{NJJYZP3R.js → U6FBRUM4.js} +1 -1
- package/dist/cdn/UIXX3XEN.js +2 -0
- package/dist/cdn/UPWAOZXQ.js +2 -0
- package/dist/cdn/{5SF6DEMO.js → VNJMTA6O.js} +1 -1
- package/dist/cdn/VOKXKU7M.js +56 -0
- package/dist/cdn/{33BF35AO.js → VYTYVWR6.js} +4 -4
- package/dist/cdn/WMZ24LWS.js +2 -0
- package/dist/cdn/{JYVBCHR6.js → WP7ORLSB.js} +1 -1
- package/dist/cdn/WS3T73IY.js +2 -0
- package/dist/cdn/{UZL6UVE4.js → ZLWWWTH4.js} +1 -1
- package/dist/cdn/{PAUIFUMO.js → ZQMBJ6MI.js} +1 -1
- package/dist/cdn/agent-utils/index.js +1 -1
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +1 -1
- package/dist/cdn/agent-utils/middlewares/middleware.js +1 -1
- package/dist/cdn/agent-utils/middlewares/trace.js +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/adapter.js +938 -1938
- package/dist/chunks/adapter10.js +21 -0
- package/dist/chunks/adapter11.js +30 -0
- package/dist/chunks/adapter12.js +22 -0
- package/dist/chunks/adapter13.js +22 -0
- package/dist/chunks/adapter14.js +109 -0
- package/dist/chunks/adapter15.js +40 -0
- package/dist/chunks/adapter16.js +154 -0
- package/dist/chunks/adapter17.js +141 -0
- package/dist/chunks/adapter18.js +127 -0
- package/dist/chunks/adapter2.js +52 -0
- package/dist/chunks/adapter3.js +30 -0
- package/dist/chunks/adapter4.js +50 -0
- package/dist/chunks/adapter5.js +27 -0
- package/dist/chunks/adapter6.js +24 -0
- package/dist/chunks/adapter7.js +26 -0
- package/dist/chunks/adapter8.js +21 -0
- package/dist/chunks/adapter9.js +42 -0
- package/dist/chunks/arcgisKnowledgeGraph.js +5 -5
- package/dist/chunks/dataExplorationGraph.js +30 -27
- package/dist/chunks/fetchAgentContext.js +13 -0
- package/dist/chunks/fetchService.js +10 -0
- package/dist/chunks/formatFeatureAttributes.js +132 -0
- package/dist/chunks/generateLayerDescriptions.js +145 -148
- package/dist/chunks/helpGraph.js +11 -9
- package/dist/chunks/layerStylingGraph.js +22 -21
- package/dist/chunks/mergeWhereClauses.js +15 -0
- package/dist/chunks/navigationGraph.js +68 -57
- package/dist/chunks/types.js +59 -0
- package/dist/components/arcgis-assistant-agent/customElement.js +404 -279
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +15 -5
- package/dist/components/arcgis-assistant-help-agent/customElement.js +21 -5
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +39 -22
- package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +22 -5
- package/dist/components/arcgis-assistant-navigation-agent/customElement.js +13 -5
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/dist/types/stencil.d.ts +2 -2
- package/dist/utils/index.d.ts +4 -5
- package/dist/utils/index.js +19 -20
- package/package.json +8 -8
- package/dist/cdn/55M2HE4U.js +0 -2
- package/dist/cdn/5RZGG4F2.js +0 -2
- package/dist/cdn/BAB3MK4Y.js +0 -2
- package/dist/cdn/BMBV6Y2A.js +0 -2
- package/dist/cdn/D3RKQSWS.js +0 -2
- package/dist/cdn/E7KEOJZG.js +0 -208
- package/dist/cdn/IGQFAL3H.js +0 -2
- package/dist/cdn/LUY6V4TP.js +0 -181
- package/dist/cdn/NSXX2KYS.js +0 -2
- package/dist/cdn/OFRFP4BX.js +0 -2
- package/dist/cdn/OUFGJV3R.js +0 -2
- package/dist/cdn/RWM5T4XB.js +0 -180
- package/dist/cdn/SRFLL6ET.js +0 -2
- package/dist/cdn/WDOM6Z5O.js +0 -18
- package/dist/cdn/WZFC5HUX.js +0 -56
- package/dist/cdn/Z4XUJQ2I.js +0 -36
- package/dist/cdn/ZJEWP2ND.js +0 -44
package/dist/cdn/WZFC5HUX.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import{J as qe,La as te,Ma as nt,Oa as W,Pa as Et,S as xt,Sa as Ie,U as tt,Ua as ge,Va as Oe,Wa as At,_ as St,a as ut,b as A,f as $,j as L,k as H,ra as Ae,ua as kt,x as mt,y as ft}from"./E7KEOJZG.js";import{$a as gt,$b as he,Ab as bt,I as Ge,Ib as F,Jb as le,Lb as vt,Ob as Se,Qb as Ct,Tb as a,U as T,Ua as Ke,Vb as Qe,Xa as z,Xb as ke,Ya as ie,Z as pt,_a as Ye,ac as K,bb as Xe,c as Je,ca as M,db as wt,dc as ce,fa as Ve,fc as Ee,oa as Q,ob as pe,pb as _e,sa as Ze,sb as xe,sc as et,ta as U,uc as _t,wb as Mt,yb as Tt,yc as ot,za as ht,zb as ee}from"./LUY6V4TP.js";import{Dd as B,s as yt}from"./MWYBF3F3.js";var rt=Symbol.for("AgentMiddleware");function O(e){return{[rt]:!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,streamTransformers:e.streamTransformers}}var Re=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.")}},Pe=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}},we=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(o=>`
|
|
3
|
-
- ${o}`).join("")}.`),this.toolName=e,this.errors=t}},je=class extends Error{toolCall;toolError;constructor(e,t){let o=e instanceof Error?e:new Error(String(e)),n=JSON.stringify(t.args);super(`Error invoking tool '${t.name}' with kwargs ${n} with error: ${o.stack}
|
|
4
|
-
Please fix the error and try again.`),this.toolCall=t,this.toolError=o}},ye=class It extends Error{static"~brand"="MiddlewareError";constructor(t,o){let n=t instanceof Error?t.message:String(t);super(n),this.name=t instanceof Error?t.name:`${o[0].toUpperCase()+o.slice(1)}Error`,t instanceof Error&&(this.cause=t)}static wrap(t,o){return mt(t)?t:new It(t,o)}static isInstance(t){return t instanceof Error&&"~brand"in t&&t["~brand"]==="MiddlewareError"}};function Me(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function de(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_getModelInstance"in e&&typeof e._getModelInstance=="function"}var Ot=!0,ho=0,G=class st{constructor(t,o,n){this.schema=t,this.tool=o,this.options=n}get name(){return this.tool.function.name}static fromSchema(t,o){function n(s){return s??`extract-${++ho}`}if(pe(t)||xe(t)){let s=ke(t);return new st(s,{type:"function",function:{name:n(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},o)}let r;return typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?r=t:r={name:n(t.title),description:t.description??"",parameters:t.schema||t},new st(ke(t),{type:"function",function:r},o)}parse(t){let o=new Qe(this.schema).validate(t);if(!o.valid)throw new we(this.name,o.errors.map(n=>n.error));return t}},oe=class Rt{_schemaType;schema;strict;constructor(t,o){if("schema"in t&&typeof t.schema=="object"&&t.schema!==null&&!("type"in t)){let n=t;this.schema=n.schema,this.strict=n.strict??Ot}else this.schema=t,this.strict=o??Ot}static fromSchema(t,o){return new Rt(ke(t),o)}parse(t){let o;if(typeof t.content=="string")o=t.content;else if(Array.isArray(t.content)){for(let n of t.content)if(typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text=="string"){o=n.text;break}}if(!(!o||o===""))try{let n=JSON.parse(o);return new Qe(this.schema).validate(n).valid?n:void 0}catch{}}};function Pt(e,t,o){if(!e)return[];if(typeof e=="object"&&e!==null&&"__responseFormatUndefined"in e)return[];if(Array.isArray(e)){if(e.every(r=>r instanceof G||r instanceof oe))return e;if(e.every(r=>pe(r)))return e.map(r=>G.fromSchema(r,t));if(e.every(r=>F(r)))return e.map(r=>G.fromSchema(r,t));if(e.every(r=>typeof r=="object"&&r!==null&&!F(r)&&!pe(r)))return e.map(r=>G.fromSchema(r,t));throw new Error(`Invalid response format: list contains mixed types.
|
|
5
|
-
All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(e instanceof G||e instanceof oe)return[e];let n=go(o);if(pe(e))return n?[oe.fromSchema(e)]:[G.fromSchema(e,t)];if(F(e))return n?[oe.fromSchema(e)]:[G.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return n?[oe.fromSchema(e)]:[G.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function go(e){return!e||!Me(e)||!("profile"in e)||typeof e.profile!="object"||!e.profile?!1:"structuredOutput"in e.profile&&e.profile.structuredOutput===!0}function wo(e,t){if(e.length<t.length||e.length>t.length+1)return!1;for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return!1;return!0}function yo(e){let t;try{t=JSON.parse(e)}catch{return!1}return!Array.isArray(t)||t.length===0?!1:t.every(o=>{if(o==null||typeof o!="object")return!1;let n=o;return typeof n.id=="string"&&"value"in n})}function Mo(e){if(e==null||typeof e!="object")return!1;let t=e;return t.type!=="constructor"||!Array.isArray(t.id)?!1:t.id[t.id.length-1]==="ToolMessage"}function To(e){return T.isInstance(e)?e.content:Mo(e)?e.kwargs?.content:e}function Te(e){return()=>{let t=Ae.local(),o=new Map;function n(r,s,i){if(o.has(r))return;let l=typeof i=="string"?JSON.parse(i):i,m,c,u,g,d=new Promise((x,y)=>{m=x,c=y}),f=new Promise(x=>{u=x}),h=new Promise(x=>{g=x});o.set(r,{resolveOutput:m,rejectOutput:c,resolveStatus:u,resolveError:g}),t.push({name:s,callId:r,input:l,output:d,status:f,error:h})}return{__native:!0,init:()=>({toolCalls:t}),process(r){if(!wo(r.params.namespace,e))return!0;if(r.method==="messages"){let s=r.params.data;if(s.event==="content-block-finish"){let i=s.contentBlock??s.content_block;i?.type==="tool_call"&&n(String(i.id??""),String(i.name??""),i.args??i.input)}}if(r.method==="tools"){let s=r.params.data,i=s.tool_call_id;s.event==="tool-started"&&n(i,s.tool_name??"unknown",s.input);let l=i?o.get(i):void 0;if(l){if(s.event==="tool-finished")l.resolveOutput(To(s.output)),l.resolveStatus("finished"),l.resolveError(void 0),o.delete(i);else if(s.event==="tool-error"){let m=s.message??"unknown error";if(yo(m))return!0;l.rejectOutput(new Error(m)),l.resolveStatus("error"),l.resolveError(m),o.delete(i)}}}return!0},finalize(){for(let r of o.values())r.resolveStatus("finished"),r.resolveError(void 0),r.resolveOutput(void 0);o.clear(),t.close()},fail(r){for(let s of o.values())s.resolveStatus("error"),s.resolveError(r instanceof Error?r.message:String(r)),s.rejectOutput(r);o.clear(),t.fail(r)}}}}function Y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(e){return e.join("\0")}function jt(e,t){if(t.length>e.length)return!1;for(let o=0;o<t.length;o+=1)if(e[o]!==t[o])return!1;return!0}function Ne(e=[]){return()=>{let t=Ae.local(),o=new Map,n=new Map,r=new Map,s=new Map,i=e.length;function l(d,f){let h=be(d);if(o.has(h))return;let x=(Y(f)&&Y(f.metadata)?f.metadata:void 0)?.lc_agent_name;o.set(h,typeof x=="string"?x:void 0)}function m(d){if(!Y(d))return;let f=d.id;if(typeof f!="string")return;let h=d.input,x;if(Y(h)&&Y(h.tool_call)){let y=h.tool_call.id;typeof y=="string"&&(x=y)}else if(Array.isArray(h)){for(let y of h)if(Y(y)&&typeof y.id=="string"){x=y.id;break}}x!=null&&n.set(f,x)}function c(d){let f=r.get(be(d));if(typeof f=="string"&&f.length>0)return{type:"toolCall",tool_call_id:f};let h=d[d.length-1],x=h.indexOf(":");if(x===-1)return;let y=h.slice(x+1);if(y.length===0)return;let w=n.get(y);if(!(typeof w!="string"||w.length===0))return{type:"toolCall",tool_call_id:w}}function u(d){if(d.length!==i+1||!jt(d,e))return;let f=be(d);if(s.has(f))return;let h=o.get(f);if(typeof h!="string"||h.length===0)return;let x=kt(d),y=x.init(),w=Te(d)(),P=w.init(),I=Ne(d)(),j=I.init(),Z,N,b=new Promise((J,ae)=>{Z=J,N=ae});s.set(f,{key:f,path:d,name:h,messages:x,toolCall:w,nested:I,resolveOutput:Z,rejectOutput:N,latestValues:void 0,done:!1}),t.push({name:h,cause:c(d),output:b,messages:y.messages,toolCalls:P.toolCalls,subagents:j.subagents})}function g(d,f){d.done||(d.done=!0,f.type==="resolve"?d.resolveOutput(d.latestValues):d.rejectOutput(f.error),d.messages.finalize?.(),d.toolCall.finalize?.(),d.nested.finalize?.())}return{__native:!0,init:()=>({subagents:t}),process(d){let f=d.params.namespace,h=d.params.data,x=d.method==="tasks"&&Y(h)&&"result"in h;d.method==="tools"&&Y(h)&&h.event==="tool-started"&&typeof h.tool_call_id=="string"&&h.tool_call_id.length>0&&r.set(be(f),h.tool_call_id),d.method==="tasks"&&!x&&(l(f,h),m(h),u(f));for(let y of s.values())if(!y.done&&jt(f,y.path)&&(y.messages.process(d),y.toolCall.process(d),y.nested.process(d),be(f)===y.key)){if(d.method==="values"&&Y(h))y.latestValues=h;else if(d.method==="lifecycle"&&Y(h)){let w=h.event;w==="completed"||w==="interrupted"?g(y,{type:"resolve"}):w==="failed"&&g(y,{type:"reject",error:new Error(`Subagent ${y.name} failed`)})}}return!0},finalize(){for(let d of s.values())g(d,{type:"resolve"});t.close()},fail(d){for(let f of s.values())g(f,{type:"reject",error:d});t.fail(d)}}}}var at=Symbol.for("langgraph-zod");at in globalThis||(globalThis[at]=new WeakSet);function Nt(e){let t=globalThis[at];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){let o=this;return{metadata(n){return Oe(o,{jsonSchemaExtra:n})},reducer(n,r){return Oe(o,{default:Se(o),reducer:{schema:r,fn:n}})}}}}),t.add(e))}try{Nt(a.ZodType.prototype),Nt(B.ZodType.prototype)}catch(e){throw new 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})}var Lt=class extends yt{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let o=t[0];if(o&&!o?.default){let n=Se(e);n!=null&&(o.default=n)}return super.add(e,...t)}},bo=new Lt(ge);function Dt(e=!0,t,o=[]){let n={jumpTo:new nt},r={},s={},i=l=>{if(W.isInstance(l)){for(let[c,u]of Object.entries(l.fields))if(!(c in n)){if(n[c]=u,c.startsWith("_"))continue;te.isInstance(u)?(r[c]=u.inputSchema||u.valueSchema,s[c]=u.valueSchema):(r[c]=u,s[c]=u)}return}let m=le(l);for(let[c,u]of Object.entries(m)){let g=c.startsWith("_");if(!(c in n)){if(_e(u)){let d=ge.get(u);if(d?.reducer){d.reducer.schema?(n[c]=new te(u,{inputSchema:d.reducer.schema,reducer:d.reducer.fn}),g||(r[c]=d.reducer.schema,s[c]=u)):(n[c]=new te(u,{reducer:d.reducer.fn}),g||(r[c]=u,s[c]=u));continue}}n[c]=u,g||(r[c]=u,s[c]=u)}}};t&&(W.isInstance(t)||F(t))&&i(t);for(let l of o)l.stateSchema&&(W.isInstance(l.stateSchema)||F(l.stateSchema))&&i(l.stateSchema);return e&&(s.structuredResponse=new nt),{state:new W({messages:Ie,...n}),input:new W({messages:Ie,...r}),output:new W({messages:Ie,...s})}}var it=/<name>(.*?)<\/name>/s,lt=/<content>(.*?)<\/content>/s;function vo(e,t){if(W.isInstance(e)){let o={};for(let n of Object.keys(e.fields))n in t&&(o[n]=t[n]);return o}if(xe(e))return ee(e,t);throw new Error(`Invalid state schema type: ${typeof e}`)}function Bt(e){if(!M.isInstance(e)||Ve.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content=="string")return new M({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let o=[],n=0;for(let r of e.content)typeof r=="string"?(n+=1,o.push(`<name>${t}</name><content>${r}</content>`)):typeof r=="object"&&"type"in r&&r.type==="text"?(n+=1,o.push({...r,text:`<name>${t}</name><content>${r.text}</content>`})):o.push(r);return n||o.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new M({...e.lc_kwargs,content:o,name:void 0})}function Ut(e){if(!M.isInstance(e)||!e.content)return e;let t=[],o;if(Array.isArray(e.content))t=e.content.filter(n=>{if(n.type==="text"&&typeof n.text=="string"){let r=n.text.match(it),s=n.text.match(lt);return r&&(!s||s[1]==="")?(o=r[1],!1):!0}return!0}).map(n=>{if(n.type==="text"&&typeof n.text=="string"){let r=n.text.match(it),s=n.text.match(lt);return!r||!s?n:(o=r[1],{...n,text:s[1]})}return n});else{let n=e.content,r=n.match(it),s=n.match(lt);if(!r||!s)return e;o=r[1],t=s[1]}return new M({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:o})}function se(e){return he.isRunnable(e)}function $t(e){return Me(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}var ct=(e,t,o={})=>{if($t(e))return e.bindTools(t,o);if(K.isRunnableBinding(e)&&$t(e.bound)){let n=e.bound.bindTools(t,o);return K.isRunnableBinding(n)?new K({bound:n.bound,config:{...e.config,...n.config},kwargs:{...e.kwargs,...n.kwargs},configFactories:n.configFactories??e.configFactories}):new K({bound:n,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Le(e){if(typeof e=="function")return;let t=e;if(ce.isRunnableSequence(t)&&(t=t.steps.find(o=>K.isRunnableBinding(o))||t),!de(t)){if(K.isRunnableBinding(t)){let o=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(o||n)throw new Re}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new Re}}function ue(e){return!!(M.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function zt(e){if(e==null)return new U("");if(U.isInstance(e))return e;if(typeof e=="string")return new U({content:[{type:"text",text:e}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof e}`)}async function Ft(e,t,o={}){let n=ct(e,t,o);if(n)return n;if(de(e)){let r=ct(await e._getModelInstance(),t,o);if(r)return r}if(ce.isRunnableSequence(e)){let r=e.steps.findIndex(s=>K.isRunnableBinding(s)||Me(s)||de(s));if(r>=0){let s=ct(e.steps[r],t,o);if(s){let i=e.steps.slice();return i.splice(r,1,s),ce.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function Co(e){if(e.length===0)return;if(e.length===1)return e[0];function t(n,r){return async(s,i)=>n(s,async m=>r(m,i))}let o=e[e.length-1];for(let n=e.length-2;n>=0;n--)o=t(e[n],o);return o}function Wt(e){let t=e.filter(o=>o.wrapToolCall);if(t.length!==0)return Co(t.map(o=>{let n=o.wrapToolCall;return async(s,i)=>{let l=s.state,m=async c=>{let u={...l,...c.state};return i({...c,state:u})};try{let c=await n({...s,state:{messages:l.messages,...o.stateSchema?vo(o.stateSchema,{...l}):{}}},m);if(!T.isInstance(c)&&!H(c))throw new Error(`Invalid response from "wrapToolCall" in middleware "${o.name}": expected ToolMessage or Command, got ${typeof c}`);return c}catch(c){throw ye.wrap(c,o.name)}}}))}var _o=["tags","metadata","runName","maxConcurrency","recursionLimit","configurable"];function Ht(e){let t={};for(let o of _o){let n=e[o];n!==void 0&&(t[o]=n)}return t}async function Jt(e,t){let o={};for(let n of e){if(!n.stateSchema)continue;let r;if(W.isInstance(n.stateSchema)){let l={};for(let[m,c]of Object.entries(n.stateSchema.fields))te.isInstance(c)?l[m]=c.inputSchema||c.valueSchema:l[m]=c;r=B.object(l)}else if(F(n.stateSchema))r=n.stateSchema;else continue;let s=await Mt(Ct(r,l=>l.startsWith("_")),t);if(s.success){Object.assign(o,s.data);continue}let i=s.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
|
|
6
|
-
`);throw new Error(`Middleware "${n.name}" has required state fields that must be initialized:
|
|
7
|
-
${i}
|
|
8
|
-
|
|
9
|
-
To fix this, either:
|
|
10
|
-
1. Provide default values in your middleware's state schema using .default():
|
|
11
|
-
stateSchema: z.object({
|
|
12
|
-
myField: z.string().default("default value")
|
|
13
|
-
})
|
|
14
|
-
|
|
15
|
-
2. Or make the fields optional using .optional():
|
|
16
|
-
stateSchema: z.object({
|
|
17
|
-
myField: z.string().optional()
|
|
18
|
-
})
|
|
19
|
-
|
|
20
|
-
3. Or ensure you pass these values when invoking the agent:
|
|
21
|
-
agent.invoke({
|
|
22
|
-
messages: [...],
|
|
23
|
-
${s.error.issues[0]?.path.join(".")}: "value"
|
|
24
|
-
})`)}return o}function Gt(e){let t={messages:B.custom(()=>[]),structuredResponse:B.any().optional()};if(!e)return B.object(t);let o;if(W.isInstance(e)){o={};for(let[r,s]of Object.entries(e.fields))te.isInstance(s)?o[r]=s.inputSchema||s.valueSchema:o[r]=s}else if(F(e))o=le(e);else return B.object(t);let n={...t};for(let[r,s]of Object.entries(o))r.startsWith("_")?n[r]=s.optional():n[r]=s;return B.object(n)}function Vt(e){if(F(e))return vt(e);if(W.isInstance(e)){let t={};for(let[o,n]of Object.entries(e.fields)){let r;te.isInstance(n)?r=n.inputSchema||n.valueSchema:r=n,t[o]=_e(r)?r.optional():B.any().optional()}return B.object(t)}return B.object({})}function V(e){if(e){if(["model_request","tools",A].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return A;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function De(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}var Be={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:{package:"@langchain/google",className:"ChatGoogle"},"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"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},Kt=Object.keys(Be);async function So(e,t){let o;if(t)o=Be[t];else{let n=Object.entries(Be).find(([,r])=>r.className===e);o=n?n[1]:void 0}if(o)try{return(await import(o.package))[o.className]}catch(n){let r=n;if("code"in r&&r.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in r&&typeof r.message=="string"){let s=(r.message.startsWith("Error: ")?r.message.slice(7):r.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw n}}async function ko(e,t,o={}){let n=t||Eo(e);if(!n)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let r=Be[n];if(!r){let l=Kt.join(", ");throw new Error(`Unsupported { modelProvider: ${n} }.
|
|
25
|
-
|
|
26
|
-
Supported model providers are: ${l}`)}let{modelProvider:s,...i}=o;return new(await So(r.className,n))({model:e,...i})}function Eo(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("gpt-5")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?"openai":e.startsWith("claude")?"anthropic":e.startsWith("command")?"cohere":e.startsWith("accounts/fireworks")?"fireworks":e.startsWith("gemini")?"google-vertexai":e.startsWith("amazon.")?"bedrock":e.startsWith("mistral")?"mistralai":e.startsWith("sonar")||e.startsWith("pplx")?"perplexity":void 0}var Zt=class $e extends tt{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(t){super(t),this._defaultConfig=t.defaultConfig??{},t.configurableFields==="any"?this._configurableFields="any":this._configurableFields=t.configurableFields??["model","modelProvider"],t.configPrefix?this._configPrefix=t.configPrefix.endsWith("_")?t.configPrefix:`${t.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=t.queuedMethodOperations??this._queuedMethodOperations,this._profile=t.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(t){let o=this._getCacheKey(t),n=this._modelInstanceCache.get(o);if(n)return n;let r={...this._defaultConfig,...this._modelParams(t)},s=await ko(r.model,r.modelProvider,r);for(let[i,l]of Object.entries(this._queuedMethodOperations))i in s&&typeof s[i]=="function"&&(s=await s[i](...l));return this._modelInstanceCache.set(o,s),s}async _generate(t,o,n){return(await this._getModelInstance(o))._generate(t,o??{},n)}bindTools(t,o){let n={...this._queuedMethodOperations};return n.bindTools=[t,o],new $e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})}withStructuredOutput=(t,...o)=>{let n={...this._queuedMethodOperations};return n.withStructuredOutput=[t,...o],new $e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:n})};_modelParams(t){let o=t?.configurable??{},n={};for(let[r,s]of Object.entries(o))if(r.startsWith(this._configPrefix)){let i=this._removePrefix(r,this._configPrefix);n[i]=s}return this._configurableFields!=="any"&&(n=Object.fromEntries(Object.entries(n).filter(([r])=>this._configurableFields.includes(r)))),n}_removePrefix(t,o){return t.startsWith(o)?t.slice(o.length):t}withConfig(t){let o={...t||{}},n=this._modelParams(o),r=Object.fromEntries(Object.entries(o).filter(([s])=>s!=="configurable"));return r.configurable=Object.fromEntries(Object.entries(o.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(n).includes(this._removePrefix(s,this._configPrefix)))),new K({config:o,bound:new $e({defaultConfig:{...this._defaultConfig,...n},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(t,o){let n=await this._getModelInstance(o),r=ie(o);return n.invoke(t,r)}async stream(t,o){let n=new wt({generator:await(await this._getModelInstance(o)).stream(t,o),config:o});return await n.setup,Xe.fromAsyncGenerator(n)}async batch(t,o,n){return super.batch(t,o,n)}async*transform(t,o){let n=await this._getModelInstance(o),r=ie(o);yield*n.transform(t,r)}async*streamLog(t,o,n){let r=await this._getModelInstance(o),s=ie(o);yield*r.streamLog(t,s,{...n,_schemaFormat:"original",includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(t,o,n){if(o?.version==="v1"||o?.version==="v2"){let i=this,l=o;async function*m(){let c=await i._getModelInstance(l),u={...ie(l),version:l.version,...l.encoding!==void 0?{encoding:l.encoding}:{}},g;l.version==="v1"&&l.encoding==="text/event-stream"||l.version==="v1"||l.version==="v2"&&l.encoding,g=c.streamEvents(t,u,n);for await(let d of g)yield d}return Xe.fromAsyncGenerator(m())}let r=this;async function*s(){let i=await r._getModelInstance(o),l=ie(o);yield*i.streamEvents(t,l)}return new xt(s())}get profile(){if(this._profile)return this._profile;let t=this._getCacheKey({});return this._modelInstanceCache.get(t)?.profile??{}}_getCacheKey(t){let o=t??{};if(o.configurable){let{configurable:n}=o,r={};for(let[s,i]of Object.entries(n))s.startsWith("__pregel_")||(r[s]=i);o={...o,configurable:r}}return JSON.stringify(o)}};async function q(e,t){let{configurableFields:o,configPrefix:n,modelProvider:r,profile:s,...i}={configPrefix:"",...t??{}};if(r===void 0&&e?.includes(":")){let[u,...g]=e.split(":"),d=g.length===0?[u]:[u,g.join(":")];Kt.includes(d[0])&&([r,e]=d)}let l=Array.isArray(o)?[...o]:o;!e&&l===void 0&&(l=["model","modelProvider"]),n&&l===void 0&&console.warn(`{ configPrefix: ${n} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let m={...i},c;return l===void 0?c=new Zt({defaultConfig:{...m,model:e,modelProvider:r},configPrefix:n,profile:s}):(e&&(m.model=e),r&&(m.modelProvider=r),c=new Zt({defaultConfig:m,configPrefix:n,configurableFields:l,profile:s})),await c._getModelInstance(),c}var me=class extends he{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 o=z(this.config,t),n=await Ke.runWithConfig(o,async()=>this.func(e,o));return he.isRunnable(n)&&this.recurse?await Ke.runWithConfig(o,async()=>n.invoke(e,o)):(this.#e=n,n)}};function Yt(e,t){let o,n;if(t==="inline")o=Bt,n=Ut;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function r(s){return s.map(o)}return ce.from([Ee.from(r),e,Ee.from(n)])}function Ao(e){return M.isInstance(e)||H(e)||typeof e=="object"&&e!==null&&"structuredResponse"in e&&"messages"in e}var R="model_request",Xt=class extends me{#e;#o;constructor(e){super({name:e.name??"model",func:(t,o)=>this.#t(t,o)}),this.#e=e,this.#o=e.systemMessage}async#r(e,t=this.#e.responseFormat){if(!t)return;let o;de(e)?o=await e._getModelInstance():typeof e!="string"&&(o=e);let n=Pt(t,void 0,o);if(n.length!==0)return n.every(r=>r instanceof oe)?{type:"native",strategy:n[0]}:{type:"tool",tools:n.filter(r=>r instanceof G).reduce((r,s)=>(r[s.name]=s,r),{})}}async#t(e,t){let o=e.messages.at(-1);if(o&&T.isInstance(o)&&o.name&&this.#e.shouldReturnDirect.has(o.name))return[new L({update:{messages:[]}})];let{response:n,lastAiMessage:r,collectedCommands:s}=await this.#a(e,t);if(typeof n=="object"&&n!==null&&"structuredResponse"in n&&"messages"in n){let{structuredResponse:m,messages:c}=n;return{messages:[...e.messages,...c],structuredResponse:m}}let i=[],l=M.isInstance(n)?n:r;return l&&(l.name=this.name,l.lc_kwargs.name=this.name,this.#c(e,l)?i.push(new L({update:{messages:[new M({content:"Sorry, need more steps to process this request.",name:this.name,id:l.id})]}})):i.push(new L({update:{messages:[l]}}))),H(n)&&!s.includes(n)&&i.push(n),i.push(...s),i}#s(){if(typeof this.#e.model=="string")return q(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(e,t,o={}){let n=await this.#s(),r=t,s=this.#o,i=null,l=[],m=async d=>{Le(d.model);let f=await this.#r(d.model,d.responseFormat),h=await this.#d(d.model,d,f),x=[...s.text===""?[]:[s],...d.messages],y=De(this.#e.signal,t.signal),w=await gt(h.invoke(x,{...t,signal:y}),y);if(i=w,f?.type==="native"){let j=f.strategy.parse(w);if(j)return{structuredResponse:j,messages:[w]};if(!w.tool_calls||w.tool_calls.length===0)throw new we(typeof f.strategy.schema?.title=="string"?f.strategy.schema.title:"providerStrategy",["Model output did not satisfy the provided response schema."]);return w}if(!f||!w.tool_calls)return w;let P=w.tool_calls.filter(j=>j.name in f.tools);if(P.length===0)return w;if(P.length>1)return this.#i(w,P,f);let I=f.tools[P[0].name]?.options?.toolMessageContent;return this.#l(w,P[0],f,I??o.lastMessage)},c=this.#e.wrapModelCallHookMiddleware??[],u=m;for(let d=c.length-1;d>=0;d--){let f=c[d],h=Array.isArray(f)?f[0]:f;if(h.wrapModelCall){let x=u,y=h;u=async w=>{let P=s,I=y.contextSchema?ee(y.contextSchema,r?.context||{}):r?.context,j=Object.freeze({context:I,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal}),Z={...w,state:{...h.stateSchema?ee(Vt(h.stateSchema),e):{},messages:e.messages},runtime:j},N=async b=>{s=P;let J=b.tools??[],ae=new Map(this.#e.toolClasses.filter(se).map(_=>[_.name,_])),Ce=J.filter(_=>se(_)&&!ae.has(_.name)),fe=J.filter(_=>{if(!se(_))return!1;let v=ae.get(_.name);return v!=null&&v!==_});if(Ce.length>0&&!this.#e.middleware?.some(_=>_.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${y.name}": ${Ce.map(_=>_.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(fe.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${y.name}": ${fe.map(_=>_.name).join(", ")}. This is not supported.`);let p=b,C=b.systemPrompt!==s.text,E=b.systemMessage!==s;if(C&&E)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");C&&(s=new U({content:[{type:"text",text:b.systemPrompt}]}),p={...b,systemPrompt:s.text,systemMessage:s}),E&&(s=new U({...b.systemMessage}),p={...b,systemPrompt:s.text,systemMessage:s});let k=await x(p);return H(k)&&i?(l.includes(k)||l.push(k),i):k};if(!y.wrapModelCall)return N(Z);try{let b=await y.wrapModelCall(Z,N);if(!Ao(b))throw new Error(`Invalid response from "wrapModelCall" in middleware "${y.name}": expected AIMessage or Command, got ${typeof b}`);return M.isInstance(b)?i=b:H(b)&&l.push(b),b}catch(b){throw ye.wrap(b,y.name)}}}}s=this.#o;let g={model:n,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:r?.context,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal})};return{response:await u(g),lastAiMessage:i,collectedCommands:l}}#i(e,t,o){let n=new Pe(t.map(r=>r.name));return this.#n(n,e,t[0],o)}#l(e,t,o,n){let r=o.tools[t.name];try{let s=r.parse(t.args);return{structuredResponse:s,messages:[e,new T({tool_call_id:t.id??"",content:JSON.stringify(s),name:t.name}),new M(n??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#n(s,e,t,o)}}async#n(e,t,o,n){let r=Object.values(n.tools).at(0)?.options?.handleError,s=o.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(r===!1)throw e;if(r===void 0||typeof r=="boolean"&&r||Array.isArray(r)&&r.some(i=>i instanceof Pe))return new L({update:{messages:[t,new T({content:e.message,tool_call_id:s})]},goto:R});if(typeof r=="string")return new L({update:{messages:[t,new T({content:r,tool_call_id:s})]},goto:R});if(typeof r=="function"){let i=await r(e);if(typeof i!="string")throw new Error("Error handler must return a string.");return new L({update:{messages:[t,new T({content:i,tool_call_id:s})]},goto:R})}return new L({update:{messages:[t,new T({content:e.message,tool_call_id:s})]},goto:R})}#c(e,t){let o=M.isInstance(t)&&t.tool_calls?.every(r=>this.#e.shouldReturnDirect.has(r.name)),n="remainingSteps"in e?e.remainingSteps:void 0;return!!(n&&(n<1&&o||n<2&&ue(e.messages.at(-1))))}async#d(e,t,o){let n={},r=Object.values(o&&"tools"in o?o.tools:{}),s=[...t?.tools??this.#e.toolClasses,...r.map(m=>m.tool)],i=t?.toolChoice||(r.length>0?"any":void 0);if(o?.type==="native"){let m=t?.modelSettings?.strict??o?.strategy?.strict??!0,c={name:o.strategy.schema?.name??"extract",description:bt(o.strategy.schema),schema:o.strategy.schema,strict:m};Object.assign(n,{response_format:{type:"json_schema",json_schema:c},outputConfig:{format:{type:"json_schema",schema:o.strategy.schema}},responseSchema:o.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:o.strategy.schema},strict:t?.modelSettings?.strict})}let l=await Ft(e,s,{...n,...t?.modelSettings,tool_choice:i});return this.#e.includeAgentName==="inline"?Yt(l,this.#e.includeAgentName):l}getState(){let e=super.getState();return{messages:[],...e&&!H(e)?e:{}}}};var Qt=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(", ")}].`,D="tools",qt=e=>Array.isArray(e)&&e.every(Ge.isInstance),Io=e=>typeof e=="object"&&e!=null&&"messages"in e&&qt(e.messages),Oo=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function Ro(e,t){return e instanceof je?new T({content:e.message,tool_call_id:t.id,name:t.name}):new T({content:`${e}
|
|
27
|
-
Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var eo=class extends me{tools;trace=!1;signal;handleToolErrors=Ro;wrapToolCall;constructor(e,t){let{name:o,tags:n,handleToolErrors:r,signal:s,wrapToolCall:i}=t??{};super({name:o,tags:n,func:(l,m)=>this.run(l,m)}),this.options=t,this.tools=e,this.handleToolErrors=r??this.handleToolErrors,this.signal=s,this.wrapToolCall=i}#e(e,t,o){if(ft(e)||this.signal?.aborted||o&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors=="function"){let n=this.handleToolErrors(e,t);if(n&&T.isInstance(n))return n;throw e}else if(this.handleToolErrors)return new T({name:t.name,content:`${e}
|
|
28
|
-
Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,o){let n=t,r={context:n?.context,store:n?.store,configurable:n?.configurable,writer:n?.writer,interrupt:n?.interrupt,signal:n?.signal},s=this.tools.find(m=>m.name===e.name),i=async m=>{let{toolCall:c,tool:u}=m,g=u??this.tools.find(f=>f.name===c.name);if(g===void 0){let f=this.tools.map(h=>h.name);return new T({content:Qt(c.name,f),tool_call_id:c.id,name:c.name,status:"error"})}let d=g;try{let f=await d.invoke({...c,type:"tool_call"},{...t,config:t,toolCallId:c.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:De(this.signal,t.signal)});return T.isInstance(f)||H(f)?f:new T({name:d.name,content:typeof f=="string"?f:JSON.stringify(f),tool_call_id:c.id})}catch(f){throw f instanceof pt?new je(f,c):f}},l={toolCall:e,tool:s,state:o,runtime:r};if(this.wrapToolCall)try{return await this.wrapToolCall(l,i)}catch(m){return this.#e(m,e,!0)}if(!s){let m=this.tools.map(c=>c.name);return new T({content:Qt(e.name,m),tool_call_id:e.id,name:e.name,status:"error"})}try{return await i(l)}catch(m){return this.#e(m,e,!1)}}async run(e,t){let o;if(Oo(e)){let{lg_tool_call:s,jumpTo:i,...l}=e;o=[await this.runTool(e.lg_tool_call,t,l)]}else{let s;if(qt(e))s=e;else if(Io(e))s=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(m=>m.getType()==="tool").map(m=>m.tool_call_id)),l;for(let m=s.length-1;m>=0;m-=1){let c=s[m];if(M.isInstance(c)){l=c;break}}if(!M.isInstance(l))throw new Error("ToolNode only accepts AIMessages as input.");o=await Promise.all(l.tool_calls?.filter(m=>m.id==null||!i.has(m.id)).map(m=>this.runTool(m,t,e))??[])}if(!o.some(H))return Array.isArray(e)?o:{messages:o};let n=[],r=null;for(let s of o)H(s)?s.graph===L.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>Po(i))?r?r.goto.push(...s.goto):r=new L({graph:L.PARENT,goto:s.goto}):n.push(s):n.push(Array.isArray(e)?[s]:{messages:[s]});return r&&n.push(r),n}};function Po(e){return e instanceof $}function Ue(e,t){let n=0;if(t&&t.length>0){let r=0;for(let s of t){let i=ot(s)?St(s):s;r+=JSON.stringify(i).length}n+=r}for(let r of e){let s;typeof r.content=="string"?s=r.content:Array.isArray(r.content)?s=r.content.map(i=>typeof i=="string"?i:i.type==="text"&&"text"in i?i.text:"").join(""):s="",M.isInstance(r)&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0&&(s+=JSON.stringify(r.tool_calls)),T.isInstance(r)&&(s+=r.tool_call_id??""),n+=s.length}return Math.ceil(n/4)}function X(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function ne(e){return typeof e=="function"?e:e.hook}var jo=class{},No=class{},re=class extends me{constructor(e){super(e)}async invokeMiddleware(e,t){let o={};if(this.middleware.contextSchema&&F(this.middleware.contextSchema)){let m=le(this.middleware.contextSchema);if(m){let c={},u=t?.context||{};for(let g of Object.keys(m))g in u&&(c[g]=u[g]);o=ee(this.middleware.contextSchema,c)}}let n={...e,messages:e.messages},r={context:o,store:t?.store,configurable:t?.configurable,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},s=await this.runHook(n,Object.freeze(Object.assign(new No,{...r,context:Object.freeze(Object.assign(new jo,o))})));if(!s)return{jumpTo:void 0};let i,l;if(this.name?.startsWith("BeforeAgentNode_")?(i=X(this.middleware.beforeAgent),l="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=X(this.middleware.beforeModel),l="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=X(this.middleware.afterAgent),l="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=X(this.middleware.afterModel),l="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!i?.includes(s.jumpTo)){let m=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:l?`no ${l} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${m}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...n,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...n,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:Gt(this.middleware.stateSchema)}}};var to=class extends re{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(e){super({name:`BeforeAgentNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return ne(this.middleware.beforeAgent)(e,t)}};var oo=class extends re{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(e){super({name:`BeforeModelNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return ne(this.middleware.beforeModel)(e,t)}};var no=class extends re{lc_namespace=["langchain","agents","afterModelNodes"];constructor(e){super({name:`AfterModelNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return ne(this.middleware.afterModel)(e,t)}};var ro=class extends re{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(e){super({name:`AfterAgentNode_${e.name}`,func:async(t,o)=>this.invokeMiddleware(t,o)}),this.middleware=e}runHook(e,t){return ne(this.middleware.afterAgent)(e,t)}};var so=class ao{#e;#o="v2";#r;#t;constructor(t,o){if(this.options=t,this.#t=z(o??{},{metadata:{ls_integration:"langchain_create_agent"},configurable:{ls_agent_type:"root"}}),t.name&&(this.#t=z(this.#t,{metadata:{lc_agent_name:t.name}})),this.#o=t.version??this.#o,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Le(t.model);let n=this.options.middleware?.filter(p=>p.tools).flatMap(p=>p.tools)??[],r=[...t.tools??[],...n],s=new Set(r.filter(se).filter(p=>"returnDirect"in p&&p.returnDirect).map(p=>p.name)),i=!!this.options.middleware?.some(p=>p.wrapModelCall),{state:l,input:m,output:c}=Dt(this.options.responseFormat!==void 0||i,this.options.stateSchema,this.options.middleware),u=new At(l,{input:m,output:c,context:this.options.contextSchema}),g=[],d=[],f=[],h=[],x=[];this.#r=new Xt({model:this.options.model,systemMessage:zt(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:r,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:x});let y=new Set,w=this.options.middleware??[];for(let p=0;p<w.length;p++){let C,E,k,_,v=w[p];if(y.has(v.name))throw new Error(`Middleware ${v.name} is defined multiple times`);if(y.add(v.name),v.beforeAgent){C=new to(v);let S=`${v.name}.before_agent`;g.push({index:p,name:S,allowed:X(v.beforeAgent)}),u.addNode(S,C,C.nodeOptions)}if(v.beforeModel){E=new oo(v);let S=`${v.name}.before_model`;d.push({index:p,name:S,allowed:X(v.beforeModel)}),u.addNode(S,E,E.nodeOptions)}if(v.afterModel){k=new no(v);let S=`${v.name}.after_model`;f.push({index:p,name:S,allowed:X(v.afterModel)}),u.addNode(S,k,k.nodeOptions)}if(v.afterAgent){_=new ro(v);let S=`${v.name}.after_agent`;h.push({index:p,name:S,allowed:X(v.afterAgent)}),u.addNode(S,_,_.nodeOptions)}v.wrapModelCall&&x.push(v)}u.addNode(R,this.#r);let P=w.some(p=>p.wrapToolCall),I=r.filter(se);if(I.length>0||P){let p=new eo(I,{signal:this.options.signal,wrapToolCall:Wt(w)});u.addNode(D,p)}let j;g.length>0?j=g[0].name:d.length>0?j=d[0].name:j=R;let Z=d.length>0?d[0].name:R,N=h.length>0?h[h.length-1].name:A;u.addEdge(ut,j);let b=I.length>0||P;for(let p=0;p<g.length;p++){let C=g[p],E=C.name,k=p===g.length-1?Z:g[p+1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._.map(S=>S===A?N:S)]));u.addConditionalEdges(E,this.#c(I,k,N,b),v)}else u.addEdge(E,k)}for(let p=0;p<d.length;p++){let C=d[p],E=C.name,k=p===d.length-1?R:d[p+1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));u.addConditionalEdges(E,this.#d(I,k,b),v)}else u.addEdge(E,k)}let J=f.at(-1);if(f.length>0&&J)u.addEdge(R,J.name);else{let p=this.#s(I,!1,b).map(C=>C===A?N:C);p.length===1?u.addEdge(R,p[0]):u.addConditionalEdges(R,this.#i(N),p)}for(let p=f.length-1;p>0;p--){let C=f[p],E=C.name,k=f[p-1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));u.addConditionalEdges(E,this.#n(I,C.allowed,k,b),v)}else u.addEdge(E,k)}if(f.length>0){let p=f[0],C=p.name,E=this.#s(I,!0,b).filter(v=>v!=="tools"||b),k=!!(p.allowed&&p.allowed.length>0),_=E.map(v=>v===A?N:v);u.addConditionalEdges(C,this.#l(I,k,N,b),_)}for(let p=h.length-1;p>0;p--){let C=h[p],E=C.name,k=h[p-1].name;if(C.allowed&&C.allowed.length>0){let _=C.allowed.map(S=>V(S)).filter(S=>S!=="tools"||b),v=Array.from(new Set([k,..._]));u.addConditionalEdges(E,this.#n(I,C.allowed,k,b),v)}else u.addEdge(E,k)}if(h.length>0){let p=h[0],C=p.name;if(p.allowed&&p.allowed.length>0){let E=p.allowed.map(_=>V(_)).filter(_=>_!=="tools"||b),k=Array.from(new Set([A,...E]));u.addConditionalEdges(C,this.#n(I,p.allowed,A,b),k)}else u.addEdge(C,A)}if(b){let p=Z;s.size>0?u.addConditionalEdges(D,this.#a(s,N,p),[p,N]):u.addEdge(D,p)}let ae=(this.options.middleware??[]).flatMap(p=>p.streamTransformers??[]),Ce=[Te([]),Ne([]),...ae,...this.options.streamTransformers??[]];this.#e=u.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description,transformers:Ce});let fe=Ht(this.#t);Object.keys(fe).length>0&&(this.#e=this.#e.withConfig(fe))}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(t){this.#e.checkpointer=t}get store(){return this.#e.store}set store(t){this.#e.store=t}withConfig(t){return new ao(this.options,z(this.#t,t))}#s(t,o=!1,n=t.length>0){let r=[];return n&&r.push(D),o&&r.push(R),r.push(A),r}#a(t,o,n){return r=>{let s=r.messages,i=s[s.length-1];return T.isInstance(i)&&i.name&&t.has(i.name)?this.options.responseFormat?n:o:n}}#i(t=A){return o=>{let n=o.messages.at(-1);if(!M.isInstance(n)||!n.tool_calls||n.tool_calls.length===0||n.tool_calls.every(s=>s.name.startsWith("extract-")))return t;if(this.#o==="v1")return D;let r=n.tool_calls.filter(s=>!s.name.startsWith("extract-"));return r.length===0?t:r.map(s=>new $(D,{...o,lg_tool_call:s}))}}#l(t,o,n,r=t.length>0){let s=!!this.options.responseFormat;return i=>{let l=i,m=l.messages,c=m.at(-1);if(M.isInstance(c)&&(!c.tool_calls||c.tool_calls.length===0))return n;if(o&&l.jumpTo){let w=V(l.jumpTo);return w===A?n:w==="tools"?r?new $(D,{...i,jumpTo:void 0}):n:new $(R,{...i,jumpTo:void 0})}let u=m.filter(T.isInstance),g=m.filter(M.isInstance).at(-1),d=g?.tool_calls?.filter(w=>!u.some(P=>P.tool_call_id===w.id));if(d&&d.length>0)return this.#o==="v1"?D:d.map(w=>new $(D,{...i,lg_tool_call:w}));let f=g?.tool_calls?.some(w=>w.name.startsWith("extract-"));if(d&&d.length===0&&!f&&s)return R;if(!M.isInstance(c)||!c.tool_calls||c.tool_calls.length===0)return n;let h=c.tool_calls.every(w=>w.name.startsWith("extract-")),x=c.tool_calls.some(w=>!w.name.startsWith("extract-"));if(h||!x)return n;if(this.#o==="v1")return D;let y=c.tool_calls.filter(w=>!w.name.startsWith("extract-"));return y.length===0?n:y.map(w=>new $(D,{...i,lg_tool_call:w}))}}#n(t,o,n,r=t.length>0){let s=new Set(o.map(i=>V(i)));return i=>{let l=i;if(l.jumpTo){let m=V(l.jumpTo);if(m===A&&s.has(A))return A;if(m==="tools"&&s.has("tools"))return r?new $(D,{...i,jumpTo:void 0}):A;if(m==="model_request"&&s.has("model_request"))return new $(R,{...i,jumpTo:void 0})}return n}}#c(t,o,n,r=t.length>0){return s=>{let i=s;if(!i.jumpTo)return o;let l=V(i.jumpTo);return l===A?n:l==="tools"?r?new $(D,{...s,jumpTo:void 0}):n:new $(R,{...s,jumpTo:void 0})}}#d(t,o,n=t.length>0){return r=>{let s=r;if(!s.jumpTo)return o;let i=V(s.jumpTo);return i===A?A:i==="tools"?n?new $(D,{...r,jumpTo:void 0}):A:new $(R,{...r,jumpTo:void 0})}}async#u(t,o){if(!this.options.middleware||this.options.middleware.length===0||t instanceof L||!t)return t;let n=await Jt(this.options.middleware,t),r={...(await this.#e.getState(o).catch(()=>({values:{}}))).values,...t};if(!r)return r;for(let[s,i]of Object.entries(n))s in r||(r[s]=i);return r}async invoke(t,o){let n=z(this.#t,o),r=await this.#u(t,n);return this.#e.invoke(r,n)}async stream(t,o){let n=z(this.#t,o),r=await this.#u(t,n);return this.#e.stream(r,n)}streamEvents(t,o,n){if(o?.version!=="v3"||n!=null){let r=z(this.#t,o),s=o?.version==="v1"||o?.version==="v2"?o.version:"v2";return this.#e.streamEvents(t,{...r,version:s},n)}return(async()=>{let{transformers:r,version:s,...i}=o??{},l=z(this.#t,i),m=await this.#u(t,l);return await this.#e.streamEvents(m,{...l,version:"v3",transformers:r})})()}async drawMermaidPng(t){let o=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(o)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,o){return this.#e.getState(t,o)}getStateHistory(t,o){return this.#e.getStateHistory(t,o)}getSubgraphs(t,o){return this.#e.getSubgraphs(t,o)}getSubgraphsAsync(t,o){return this.#e.getSubgraphsAsync(t,o)}updateState(t,o,n){return this.#e.updateState(t,o,n)}get builder(){return this.#e.builder}};function Lo(e){return new so(e)}var $o=a.function().args(a.custom()).returns(a.union([a.boolean(),a.promise(a.boolean())])),Bo=a.function().args(a.custom(),a.custom(),a.custom()).returns(a.union([a.string(),a.promise(a.string())])),Uo=["approve","edit","reject"],zo=a.enum(Uo),Fo=a.object({allowedDecisions:a.array(zo),description:a.union([a.string(),Bo]).optional(),argsSchema:a.record(a.any()).optional(),when:$o.optional()}),fa=a.object({interruptOn:a.record(a.union([a.boolean(),Fo])).optional(),descriptionPrefix:a.string().default("Tool execution requires approval")});var ze=`<role>
|
|
29
|
-
Context Extraction Assistant
|
|
30
|
-
</role>
|
|
31
|
-
|
|
32
|
-
<primary_objective>
|
|
33
|
-
Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
|
|
34
|
-
</primary_objective>
|
|
35
|
-
|
|
36
|
-
<objective_information>
|
|
37
|
-
You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
|
|
38
|
-
This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
|
|
39
|
-
</objective_information>
|
|
40
|
-
|
|
41
|
-
<instructions>
|
|
42
|
-
The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
|
|
43
|
-
You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
|
|
44
|
-
</instructions>
|
|
45
|
-
|
|
46
|
-
The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
|
|
47
|
-
|
|
48
|
-
With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
|
|
49
|
-
Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
|
|
50
|
-
|
|
51
|
-
<messages>
|
|
52
|
-
Messages to summarize:
|
|
53
|
-
{messages}
|
|
54
|
-
</messages>`,Wo="Here is a summary of the conversation to date:",Fe=20,Ho=4e3,Jo=15,io=5,Go=a.function().args(a.array(a.custom())).returns(a.union([a.number(),a.promise(a.number())])),ve=a.object({fraction:a.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:a.number().positive("Tokens must be greater than 0").optional(),messages:a.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),dt=a.object({fraction:a.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:a.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:a.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),lo=a.object({model:a.custom(),trigger:a.union([ve,a.array(ve)]).optional(),keep:dt.optional(),tokenCounter:Go.optional(),summaryPrompt:a.string().default(ze),trimTokensToSummarize:a.number().optional(),summaryPrefix:a.string().optional(),maxTokensBeforeSummary:a.number().optional(),messagesToKeep:a.number().optional()});function We(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 et(e.model);if("modelName"in e&&typeof e.modelName=="string")return et(e.modelName)}function Vo(e){let{data:t,error:o}=Tt(lo,e);if(o)throw new Error(`Invalid summarization middleware options: ${B.prettifyError(o)}`);return O({name:"SummarizationMiddleware",contextSchema:lo.extend({model:a.custom().optional()}),beforeModel:async(n,r)=>{let s=t.trigger,i=t.keep;t.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),s===void 0&&(s={tokens:t.maxTokensBeforeSummary})),t.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===Fe)&&(i={messages:t.messagesToKeep}));let l=r.context?.trigger!==void 0?r.context.trigger:s,m=r.context?.keep!==void 0?r.context.keep:i??{messages:Fe},c=dt.parse(m),u=[];l===void 0?u=[]:Array.isArray(l)?u=l.map(J=>ve.parse(J)):u=[ve.parse(l)];let g=u.some(J=>"fraction"in J)||"fraction"in c,d=typeof t.model=="string"?await q(t.model):t.model;if(g&&!We(d))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");let f=r.context?.summaryPrompt===ze?t.summaryPrompt??ze:r.context?.summaryPrompt??t.summaryPrompt??ze,h=r.context.summaryPrefix??t.summaryPrefix??Wo,x=r.context?.trimTokensToSummarize!==void 0?r.context.trimTokensToSummarize:t.trimTokensToSummarize??Ho;Zo(n.messages);let y=r.context?.tokenCounter!==void 0?r.context.tokenCounter:t.tokenCounter??Ue,w=await y(n.messages);if(!await Xo(n.messages,w,u,d))return;let{systemPrompt:P,conversationMessages:I}=Ko(n.messages),j=await Qo(I,c,y,d);if(j<=0)return;let{messagesToSummarize:Z,preservedMessages:N}=Yo(P,I,j),b=new Q({content:`${h}
|
|
55
|
-
|
|
56
|
-
${await tn(Z,d,f,y,x,r)}`,id:Je(),additional_kwargs:{lc_source:"summarization"}});return{messages:[new Ze({id:Et}),b,...N]}}})}function Zo(e){for(let t of e)t.id||(t.id=Je())}function Ko(e){return e.length>0&&U.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function Yo(e,t,o){let n=t.slice(0,o),r=t.slice(o);return e&&n.unshift(e),{messagesToSummarize:n,preservedMessages:r}}async function Xo(e,t,o,n){if(o.length===0)return!1;for(let r of o){let s=!0,i=!1;if(r.messages!==void 0&&(i=!0,e.length<r.messages&&(s=!1)),r.tokens!==void 0&&(i=!0,t<r.tokens&&(s=!1)),r.fraction!==void 0){i=!0;let l=We(n);typeof l=="number"?t<Math.floor(l*r.fraction)&&(s=!1):s=!1}if(i&&s)return!0}return!1}async function Qo(e,t,o,n){if("tokens"in t||"fraction"in t){let r=await qo(e,t,o,n);return typeof r=="number"?r:co(e,Fe)}return co(e,t.messages??Fe)}async function qo(e,t,o,n){if(e.length===0)return 0;let r;if("fraction"in t&&t.fraction!==void 0){let u=We(n);if(typeof u!="number")return;r=Math.floor(u*t.fraction)}else if("tokens"in t&&t.tokens!==void 0)r=Math.floor(t.tokens);else return;if(r<=0&&(r=1),await o(e)<=r)return 0;let s=0,i=e.length,l=e.length,m=Math.floor(Math.log2(e.length))+1;for(let u=0;u<m&&!(s>=i);u++){let g=Math.floor((s+i)/2);await o(e.slice(g))<=r?(l=g,i=g):s=g+1}if(l===e.length&&(l=s),l>=e.length){if(e.length===1)return 0;l=e.length-1}let c=fo(e,l);if(c<=l)return c;for(let u=l;u>=0;u--)if(uo(e,u))return u;return 0}function co(e,t){if(e.length<=t)return 0;let o=e.length-t,n=fo(e,o);if(n<=o)return n;for(let r=o;r>=0;r--)if(uo(e,r))return r;return 0}function uo(e,t){if(t>=e.length)return!0;if(t<e.length&&M.isInstance(e[t])&&ue(e[t]))return!1;let o=Math.max(0,t-io),n=Math.min(e.length,t+io);for(let r=o;r<n;r++){if(!ue(e[r]))continue;let s=mo(e[r]);if(en(e,r,t,s))return!1}return!0}function mo(e){let t=new Set;if(e.tool_calls)for(let o of e.tool_calls){let n=typeof o=="object"&&"id"in o?o.id:null;n&&t.add(n)}return t}function fo(e,t){if(t>=e.length||!T.isInstance(e[t]))return t;let o=new Set,n=t;for(;n<e.length&&T.isInstance(e[n]);){let r=e[n];r.tool_call_id&&o.add(r.tool_call_id),n++}for(let r=t-1;r>=0;r--){let s=e[r];if(M.isInstance(s)&&ue(s)){let i=mo(s);for(let l of o)if(i.has(l))return r}}return n}function en(e,t,o,n){for(let r=t+1;r<e.length;r++){let s=e[r];if(T.isInstance(s)&&n.has(s.tool_call_id)&&t<o!=r<o)return!0}return!1}async function tn(e,t,o,n,r,s){if(!e.length)return"No previous conversation history.";let i=await on(e,n,r);if(!i.length)return"Previous conversation was too long to summarize.";let l=ht(i);try{let m=o.replace("{messages}",l),c=z(Ye(s)??{},{metadata:{lc_source:"summarization"}}),u=(await t.invoke(m,c)).content;return typeof u=="string"?u.trim():Array.isArray(u)?u.map(g=>typeof g=="string"?g:typeof g=="object"&&g!==null&&"text"in g?g.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(m){return`Error generating summary: ${m}`}}async function on(e,t,o){if(o===void 0)return e;try{return await qe(e,{maxTokens:o,tokenCounter:async n=>t(n),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-Jo)}}var Da=a.object({model:a.string().or(a.instanceof(_t)).optional(),systemPrompt:a.string().optional(),maxTools:a.number().optional(),alwaysInclude:a.array(a.string()).optional()});var Ha=a.object({applyToInput:a.boolean().optional(),applyToOutput:a.boolean().optional(),applyToToolResults:a.boolean().optional()});var Ka=a.object({rules:a.record(a.string(),a.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var nn=["continue","error","end"],rn="continue";var sn=a.enum(nn).default(rn);a.object({toolName:a.string().optional(),threadLimit:a.number().optional(),runLimit:a.number().optional(),exitBehavior:sn});var si=a.object({threadToolCallCount:a.record(a.string(),a.number()).default({}),runToolCallCount:a.record(a.string(),a.number()).default({})});var an=a.enum(["pending","in_progress","completed"]).describe("Status of the todo"),ln=a.object({content:a.string().describe("Content of the todo item"),status:an}),fi=a.object({todos:a.array(ln).default([])});var cn="end",dn=a.object({threadLimit:a.number().optional(),runLimit:a.number().optional(),exitBehavior:a.enum(["error","end"]).optional()}),un=a.object({threadModelCallCount:a.number().default(0),runModelCallCount:a.number().default(0)}),po=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:o,runCount:n}){let r=[];typeof e=="number"&&typeof o=="number"&&r.push(`thread level call limit reached with ${o} model calls`),typeof t=="number"&&typeof n=="number"&&r.push(`run level call limit reached with ${n} model calls`),super(`Model call limits exceeded${r.length>0?`: ${r.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function mn(e){return O({name:"ModelCallLimitMiddleware",contextSchema:dn,stateSchema:un,beforeModel:{canJumpTo:["end"],hook:(t,o)=>{let n=o.context.exitBehavior??e?.exitBehavior??cn;n==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),n="error");let r=o.context.threadLimit??e?.threadLimit,s=o.context.runLimit??e?.runLimit,i=t.threadModelCallCount,l=t.runModelCallCount;if(typeof r=="number"&&r<=i){let m=new po({threadLimit:r,threadCount:i});if(n==="end")return{jumpTo:"end",messages:[new M(m.message)]};throw m}if(typeof s=="number"&&s<=l){let m=new po({runLimit:s,runCount:l});if(n==="end")return{jumpTo:"end",messages:[new M(m.message)]};throw m}return t}},afterModel:t=>({runModelCallCount:t.runModelCallCount+1,threadModelCallCount:t.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}var He=a.object({maxRetries:a.number().min(0).default(2),retryOn:a.union([a.function().args(a.instanceof(Error)).returns(a.boolean()),a.array(a.custom())]).default(()=>()=>!0),backoffFactor:a.number().min(0).default(2),initialDelayMs:a.number().min(0).default(1e3),maxDelayMs:a.number().min(0).default(6e4),jitter:a.boolean().default(!0)});var Ri=a.object({onFailure:a.union([a.literal("error"),a.literal("continue"),a.function().args(a.instanceof(Error)).returns(a.string())]).default("continue")}).merge(He);var Ui=a.object({tools:a.array(a.union([a.custom(),a.custom(),a.string()])).optional(),onFailure:a.union([a.literal("error"),a.literal("continue"),a.literal("raise"),a.literal("return_message"),a.function().args(a.instanceof(Error)).returns(a.string())]).default("continue")}).merge(He);var tl=a.object({enableCaching:a.boolean().optional(),ttl:a.enum(["5m","1h"]).optional(),minMessagesToCache:a.number().optional(),unsupportedModelBehavior:a.enum(["ignore","warn","raise"]).optional()});var sl=a.object({enableCaching:a.boolean().optional(),ttl:a.enum(["5m","1h"]).optional(),minMessagesToCache:a.number().optional(),unsupportedModelBehavior:a.enum(["ignore","warn","raise"]).optional()});export{O as a,Lo as b,Vo as c,mn as d};
|
package/dist/cdn/Z4XUJQ2I.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import c from"./3ZPPYCNL.js";import b from"./RWM5T4XB.js";import a from"./ZJEWP2ND.js";import{a as g}from"./HJG7QM2R.js";import{Wa as $,a as k,b as E}from"./E7KEOJZG.js";import{a as f}from"./VXFQANGJ.js";export default $arcgis.t(([,,,,,,{o:N,p:T},{a:b,b:x,c:v,d:C,e:F,f:R,g:L,h:_,i:I,j:M,k:Z,l:A,m:S,n:q,o:p,p:j},V])=>{var w=[C,F,R,L,_,I,M,Z,A];async function B(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=v(t,["mapView"]),c=r.map.bookmarks?.map(h=>h.name).filter(Boolean)??[],s=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((h,G)=>`${G+1}. layerId=${h.id} | title=${h.title??""} | name=${h.name??""} | score=${h.score.toFixed(2)}`).join(`
|
|
3
|
-
`):"",l=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",i=e.intent==="goToBookmark"&&c.length?`Available bookmarks:
|
|
4
|
-
${c.map(h=>`- ${h}`).join(`
|
|
5
|
-
`)}`:"",o=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
|
|
6
|
-
${s}`:"",d=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
|
|
7
|
-
${l}`:"",u={intent:e.intent,bookmarksSection:i,layersSection:o,fieldsSection:d,currentZoom:r.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},n=await T({promptText:a,modelTier:"fast",config:t,inputVariables:u,tools:w});await V(n,t);let m=(n.tool_calls?.length??0)>0,y=typeof n.text=="string"?n.text.trim():"",z=y.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:m?n:void 0},outputMessage:m?e.outputMessage:y,status:m?e.status:z?"success":"failed"}}var D=e=>{let t=typeof e=="string"?e:String(e);try{let a=JSON.parse(t);if(a&&typeof a=="object"&&typeof a.text=="string")return a}catch{console.warn("Failed to parse tool response as JSON:",t)}return{text:t}};async function J(e,t){let a=new b(w,{handleToolErrors:!1});try{let r=e.navigationInternalState.toolCallMessage;if(!r)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let{messages:c}=await a.invoke({messages:[r]},t),s="",l;for(let i of c){let o=D(i.content);o.text&&(s+=`${o.text}
|
|
8
|
-
`),o.sharedStatePatch&&(l={...l,...o.sharedStatePatch})}return await g({text:`Finished executing navigation tool: ${s}`},t),{...e,outputMessage:s,sharedStatePatch:l,status:"success",summary:s?q(s):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(r){let c=r instanceof Error?r.message:String(r);return await g({text:`Navigation tool execution failed: ${c}`},t),{...e,outputMessage:`Navigation tool execution failed: ${c}`,status:"failed",summary:`Navigation tool execution failed: ${c}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function P(e,t){let a=await S("navigation_intent_prompt"),{mapView:r}=v(t,["mapView"]),c=w.map(n=>({name:n.name,description:n.description,schema:n.schema})),s=r.map.bookmarks?.map(n=>n.name).filter(Boolean)??[],l=s.length?`Available bookmarks:
|
|
9
|
-
${s.map(n=>`- ${n}`).join(`
|
|
10
|
-
`)}`:"No bookmarks are available in this map.",i={tools:c.map(({name:n,description:m,schema:y})=>`${n}: ${m}, ${JSON.stringify(y)}`).join(`
|
|
11
|
-
`),bookmarks:l,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=f.object({intent:f.string()}),d=await N({promptText:a,config:t,inputVariables:i,schema:o,modelTier:"fast"}),u=typeof d.intent=="string"?d.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var W=.7,H=async(e,t)=>{try{await g({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=p(t,"layerSearch"),r=p(t,"layersAndFieldsRegistry"),c=p(t,"embeddingCache"),s=(await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:W,embeddingCache:c})).map(({id:i,score:o})=>{let d=r.get(i)?.layerItem;return{id:i,title:d?.title,name:d?.name??void 0,score:o}}),l;return s.length>0?l=`Vector search completed. Matching layers:
|
|
12
|
-
${s.map(i=>`- layerId=${i.id} | title=${i.title??""} | name=${i.name??""} | score=${i.score.toFixed(2)}`).join(`
|
|
13
|
-
`)}`:l="Vector search completed. No matching layers found.",await g({text:l},t),{...e,vectorSearchLayerResults:s}}catch(a){throw await g({text:`Error during vector search layers: ${a instanceof Error?a.message:String(a)}`},t),a}},O=.7,K=10,Q=async(e,t)=>{try{await g({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let a=p(t,"fieldSearch"),r=p(t,"layersAndFieldsRegistry"),c=p(t,"embeddingCache"),s=e.vectorSearchLayerResults?.map(o=>o.id)??[];if(s.length===0)return await g({text:"No candidate layers for field search"},t),e;let l=(await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:s,minScore:O,topResults:K,embeddingCache:c})).map(({layerId:o,results:d})=>{let u=r.get(o)?.fieldRegistry;return{layerId:o,layerName:r.get(o)?.layerItem.name,results:d.map(n=>{let m=u?.get(n.name);return{name:n.name,score:n.score,type:m?.type,alias:m?.alias,description:m?.description,statistics:m?.statistics,domain:m?.domain}})}}),i;return l.length>0?i=`Vector search completed. Matching layers and fields:
|
|
14
|
-
${l.map(o=>`${o.layerName??o.layerId}:
|
|
15
|
-
${o.results.map(d=>` - ${d.name} (${d.score.toFixed(2)})`).join(`
|
|
16
|
-
`)}`).join(`
|
|
17
|
-
`)}`:i=`No vector search field results found for score over ${O}.`,await g({text:i},t),{...e,vectorSearchFieldResults:l}}catch(a){throw await g({text:`Error during vector search fields: ${a instanceof Error?a.message:String(a)}`},t),a}},U=(e,t)=>j(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),X=()=>new $(x).addNode("requireNavigationServices",U).addNode("intentLLM",P).addNode("vectorSearchLayers",H).addNode("vectorSearchFields",Q).addNode("agent",B).addNode("tools",J).addEdge(k,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addEdge("tools",E),Y=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
18
|
-
This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
|
|
19
|
-
|
|
20
|
-
Supported actions:
|
|
21
|
-
- **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
|
|
22
|
-
- **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
|
|
23
|
-
- **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
|
|
24
|
-
- **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
|
|
25
|
-
- **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
|
|
26
|
-
- **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
|
|
27
|
-
- **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
|
|
28
|
-
- **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
|
|
29
|
-
|
|
30
|
-
_Example: “Zoom to Texas”_
|
|
31
|
-
_Example: “Go to the water mains layer”_
|
|
32
|
-
_Example: “Zoom to to the extent of my link chart”_
|
|
33
|
-
_Example: “Center the map on San Francisco at scale 50000”_
|
|
34
|
-
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
35
|
-
_Example: “Go to the Downtown bookmark”_
|
|
36
|
-
_Example: “Where is Mount Rainier?”_`,fe={id:"navigation",name:"Navigation Agent",description:Y,createGraph:X,workspace:x};return fe},"identity/IdentityManager","portal/Portal","request","config","core/reactiveUtils","layers/FeatureLayer",a,b,c)
|