@arcgis/ai-components 5.2.0-next.0 → 5.2.0-next.2
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/{6R6AY3D3.js → 4HU7735A.js} +1 -1
- package/dist/cdn/{METXWS7V.js → FHVXO2WG.js} +13 -13
- package/dist/cdn/{6MAINSY5.js → FL4W4VYN.js} +0 -1
- package/dist/cdn/{N2VQD46V.js → GSEPHN3A.js} +1 -1
- package/dist/cdn/{Y67XAMT4.js → JY6LLOUJ.js} +1 -1
- package/dist/cdn/{FB5DRKEB.js → MDVYQQUG.js} +1 -1
- package/dist/cdn/{EF453FJ2.js → ON2V5XI2.js} +1 -1
- package/dist/cdn/{QDO2AO53.js → S6W6HV4T.js} +1 -1
- package/dist/cdn/V5YEZSRY.js +16 -0
- package/dist/cdn/{GM3QP65I.js → X2ZDYHCG.js} +18 -5
- package/dist/cdn/{SZOVY2QU.js → YY2SBO3V.js} +1 -1
- package/dist/cdn/{LBVX2JYG.js → ZLXN7NMF.js} +1 -0
- package/dist/cdn/index.js +1 -1
- package/dist/chunks/adapter.js +107 -97
- package/dist/chunks/dataExplorationGraph.js +95 -86
- package/dist/chunks/data_explore_query_prompt.js +18 -5
- package/dist/chunks/intent_prompt.js +0 -1
- package/dist/chunks/summarize_query_response_prompt.js +1 -0
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/package.json +4 -4
- package/dist/cdn/U3QQW6VA.js +0 -16
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import c from"./
|
|
2
|
+
import c from"./FHVXO2WG.js";import a from"./GSEPHN3A.js";import{Fb as k,Q as x,a as y,b as l}from"./462JBSEV.js";import{c as b,d as A}from"./HB5A5R2E.js";import"./AMP6IALT.js";import"./OAVEHGB6.js";import{v as w,y as f}from"./OH64RMOR.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,{fetchKnowledgeGraph:J},{f:c,k:v,m:_},{K:u,L:K,M:S,N:M,O:G,P:T,Q:C,R:N,S:R,T:z,U:F,a:q,m:g,n:d,p:E}])=>{var L=[T,C,z,N,G,F,R];async function I(e,a){let i=await g("arcgis_knowledge_tool_prompt"),s=K(a),n={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,contextType:s},r=await _({promptText:i,messages:e.arcgisKnowledgeMessages,inputVariables:n,tools:L}),t=(r.tool_calls?.length??0)>0,o=typeof r.text=="string"?r.text.trim():"",h=o.length>0,p=r.content.toString();return!t&&(s==="map"||s==="knowledgeGraph")?{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:s==="map"?"No tools were found for the current view and prompt. Maps do not support changing nonspatial visibility, layout changes, or generation from queries.":"No tools were found for the current prompt and knowledge graph service. A knowledge graph service only supports search and query.",status:"success"}:{...e,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,r],outputMessage:t?p:o,status:t?e.status:h?"success":"failed",summary:p?d(p):"ArcGIS Knowledge Agent tool executed."}}async function U(e,a){let i=new q(L);try{let s=await i.invoke({messages:e.arcgisKnowledgeMessages},a),n=[];for(let t of s.messages){let o;if(typeof t.content!="string")throw new Error(`Unexpected tool message content type: ${typeof t.content}. Expected string.`);try{o=JSON.parse(t.content)}catch{throw new Error(`Failed to parse tool message content as JSON. Tool: ${t.name??"unknown"}`)}if(!o||typeof o!="object"||!("toolName"in o))throw new Error(`Parsed tool message content does not have expected structure. Parsed content: ${JSON.stringify(o)}`);n.push(o)}await c({text:`Finished executing ArcGIS Knowledge Agent tools: ${s.messages.filter(t=>t.name).map(t=>t.name).join(", ")}`},a);let r=n.filter(t=>typeof t!="string").map(t=>`- Called Tool: ${t.toolName}, Status: ${t.status}`);return{...e,outputMessage:r.join(`
|
|
3
3
|
`),summary:r.length?d(r.join(`
|
|
4
4
|
`)):"ArcGIS Knowledge Agent did not execute any tools or return any results.",arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,...s.messages],arcgisKnowledgeToolResult:n}}catch(s){let n=s instanceof Error?s.message:String(s);return await c({text:`ArcGIS Knowledge Agent tool execution failed: ${n}`},a),{...e,outputMessage:`ArcGIS Knowledge Agent tool execution failed: ${n}`,status:"failed",summary:`ArcGIS Knowledge Agent tool execution failed: ${n}`,arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages]}}}var D=(e,a)=>E([],"ArcgisKnowledge Agent")(e,a);async function j(e,a){let i=(e.arcgisKnowledgeToolResult??[]).map(h=>({...h,details:void 0})),{knowledgeGraph:s}=await S(a),n=M.getDataModelTypesSummary(s.dataModel),r={assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,toolResult:i,dataModelSummary:n},t=await v({promptText:await g("arcgis_knowledge_summarize_result_prompt"),modelTier:"default",inputVariables:r}),o=typeof t=="string"?t:t.content;return{...e,outputMessage:o,status:"success",summary:d(o),arcgisKnowledgeMessages:[...e.arcgisKnowledgeMessages,new x(o)]}}var O=()=>new k(u).addNode("requireArcgisKnowledgeServices",D).addNode("agent",I).addNode("tools",U).addNode("summarizationLLM",j).addEdge(y,"requireArcgisKnowledgeServices").addEdge("requireArcgisKnowledgeServices","agent").addConditionalEdges("agent",e=>(e.arcgisKnowledgeMessages[e.arcgisKnowledgeMessages.length-1]?.tool_calls?.length??0)>0?"tools":l).addConditionalEdges("tools",e=>e.status==="failed"?l:"summarizationLLM").addEdge("summarizationLLM",l),V=String.raw`The purpose of this agent is to work with Knowledge Graph data, a graph database technology that represents and stores data as interconnected entities (nodes) and relationships (edges).
|
|
5
5
|
This agent has two categories of skills: those that work with an active link chart visualization of a subset of the data in the knowledge graph, and those that work with the knowledge graph data more generally against the entire dataset in the service and database.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import a from"./
|
|
3
|
-
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(Ye(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Ie(e))n=e;else if(Ze(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),l;for(let u=n.length-1;u>=0;u-=1){let c=n[u];if(z(c)){l=c;break}}if(l==null||!z(l))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(l.tool_calls?.filter(u=>u.id==null||!s.has(u.id)).map(u=>this.runTool(u,t))??[])}if(!r.some(Q))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)Q(n)?n.graph===V.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>ge(s))?a?a.goto.push(...n.goto):a=new V({graph:V.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var Fn=g.Root({llmInputMessages:g({reducer:(e,t)=>j([],t),default:()=>[]})});var O=(e,t)=>t??e,ji=g.Root({...ve(),intent:g({reducer:O}),vectorSearchLayerResults:g({reducer:O,default:()=>[]}),vectorSearchFieldResults:g({reducer:O}),navigationInternalState:g({reducer:O,default:()=>({toolCallMessage:void 0})})});async function _t(e,t){let r=M.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let a=o.url,n=`${oe.assetsPath?.endsWith("/")?oe.assetsPath:`${oe.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await rt(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent||!s.location)throw new Error(`Could not find location for: ${e}`);let l=new ot({url:n,width:24,height:24}),u=new tt({geometry:s.location,symbol:l});t.graphics.removeAll(),t.graphics.add(u),await t.goTo(s.extent);let c={address:s.address??"",location:s.location?s.location.toJSON():null,extent:s.extent?s.extent.toJSON():null};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:c}}}}var qt=["mapView"];function $(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=qt.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function zt({address:e},t){let{mapView:r}=$(t);return await _t(e,r)}var jt=i.object({address:i.string().describe("The full address or place name to locate.")}),Li=h(zt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:jt});async function Lt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(n=>n.name===e);if(!o)throw new Error(`Bookmark with name "${e}" not found.`);let a=o.viewpoint;if(!a)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await t.goTo(a),{text:`Navigated to bookmark: ${e}`}}async function Ot({bookmarkName:e},t){let{mapView:r}=$(t);return await Promise.resolve(Lt(e,r))}var Dt=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),Oi=h(Ot,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Dt});async function
|
|
2
|
+
import a from"./GSEPHN3A.js";import{Bb as j,L as q,M as ee,R as z,Za as I,_a as h,g as ge,j as V,k as Q,kb as g,qb as be,u as we}from"./462JBSEV.js";export default $arcgis.t(([$e,M,Ce,,Ne,oe,tt,{addressToLocations:rt},ot,at,Re,{createRenderer:nt},{getSchemesByTag:it,getSchemes:st},{getBackgroundColorTheme:ke},{createAgeRenderer:lt,createContinuousRenderer:ct},{getSchemesByTag:pe},{createContinuousRenderer:ut},{createRenderer:dt},{getSchemesByTag:pt},{createRenderer:mt},{getSchemesByTag:ht},{createRenderer:ft},{getSchemesByTag:yt},{createRenderer:gt},{getSchemesByTag:wt},{createAgeRenderer:bt,createContinuousRenderer:vt},{createRenderer:Tt},{getSchemesByTag:St},xt,_e,qe,{formatDateOnly:Et,convertDateFormatToIntlOptions:U,formatTimeOnly:It,formatDate:Fe},$t,Nt,kt,Ft,Mt,ze,,{fetchKnowledgeGraph:Me,executeQueryStreaming:At,executeSearchStreaming:Ct},Rt,{a:i,c:L,d:ve,f:T,g:S,l:Te}])=>{var Ie=e=>Array.isArray(e)&&e.every(q),Ze=e=>typeof e=="object"&&e!=null&&"messages"in e&&Ie(e.messages),Ye=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,B=class extends be{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:o,handleToolErrors:a}=t??{};super({name:r,tags:o,func:(n,s)=>this.run(n,s)}),this.tools=e,this.handleToolErrors=a??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(o=>o.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let o=await r.invoke({...e,type:"tool_call"},t);return q(o)&&o.getType()==="tool"||Q(o)?o:new ee({status:"success",name:r.name,content:typeof o=="string"?o:JSON.stringify(o),tool_call_id:e.id})}catch(o){if(!this.handleToolErrors||we(o))throw o;return new ee({status:"error",content:`Error: ${o.message}
|
|
3
|
+
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(Ye(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if(Ie(e))n=e;else if(Ze(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),l;for(let u=n.length-1;u>=0;u-=1){let c=n[u];if(z(c)){l=c;break}}if(l==null||!z(l))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(l.tool_calls?.filter(u=>u.id==null||!s.has(u.id)).map(u=>this.runTool(u,t))??[])}if(!r.some(Q))return Array.isArray(e)?r:{messages:r};let o=[],a=null;for(let n of r)Q(n)?n.graph===V.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>ge(s))?a?a.goto.push(...n.goto):a=new V({graph:V.PARENT,goto:n.goto}):o.push(n):o.push(Array.isArray(e)?[n]:{messages:[n]});return a&&o.push(a),o}};var Fn=g.Root({llmInputMessages:g({reducer:(e,t)=>j([],t),default:()=>[]})});var O=(e,t)=>t??e,ji=g.Root({...ve(),intent:g({reducer:O}),vectorSearchLayerResults:g({reducer:O,default:()=>[]}),vectorSearchFieldResults:g({reducer:O}),navigationInternalState:g({reducer:O,default:()=>({toolCallMessage:void 0})})});async function _t(e,t){let r=M.getDefault().helperServices,o=r.geocode.find(d=>d.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!o)throw new Error("No geocoding service found in helperServices.");let a=o.url,n=`${oe.assetsPath?.endsWith("/")?oe.assetsPath:`${oe.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await rt(a,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent||!s.location)throw new Error(`Could not find location for: ${e}`);let l=new ot({url:n,width:24,height:24}),u=new tt({geometry:s.location,symbol:l});t.graphics.removeAll(),t.graphics.add(u),await t.goTo(s.extent);let c={address:s.address??"",location:s.location?s.location.toJSON():null,extent:s.extent?s.extent.toJSON():null};return{text:`Successfully zoomed to ${e}.`,sharedStatePatch:{lastResolvedLocation:{value:c}}}}var qt=["mapView"];function $(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=qt.filter(o=>!(o in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function zt({address:e},t){let{mapView:r}=$(t);return await _t(e,r)}var jt=i.object({address:i.string().describe("The full address or place name to locate.")}),Li=h(zt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:jt});async function Lt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let o=r.find(n=>n.name===e);if(!o)throw new Error(`Bookmark with name "${e}" not found.`);let a=o.viewpoint;if(!a)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await t.goTo(a),{text:`Navigated to bookmark: ${e}`}}async function Ot({bookmarkName:e},t){let{mapView:r}=$(t);return await Promise.resolve(Lt(e,r))}var Dt=I.object({bookmarkName:I.string().describe("The name of the bookmark to navigate to.")}),Oi=h(Ot,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Dt});async function Pt(e,t,r){let o=r.map?.allLayers.find(s=>s.id===e);if(!o)return{text:`Error: Layer with id ${e} not found`};let a=t?.trim()?t:"1=1",n=o.createQuery();n.where=a;try{let{extent:s,count:l}=await o.queryExtent(n);if(l===0)return{text:`No features found in ${o.title} matching: ${a}`,where:a};if(s)await r.goTo(s);else return{text:`Error: Unable to determine extent for ${o.title}`,where:a};let u={layerId:e,layerTitle:o.title??e,where:a,count:l};return{text:`Successfully zoomed to ${l} feature(s) in ${o.title} matching: ${a}`,where:a,sharedStatePatch:{lastNavigatedFeatures:{value:u}}}}catch(s){return console.error("Error in goToFeatures:",s),{text:`Error: ${s instanceof Error?s.message:"Unknown error"}`,where:a}}}async function Gt({layerId:e,where:t},r){let{mapView:o}=$(r);return await Pt(e,t,o)}var Vt=I.object({layerId:I.string().describe("The layerId of the layer to zoom to."),where:I.string().describe("The sql-92 where clause used to query features to zoom to")}),Di=h(Gt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Vt});async function Qt(e){let t=new at({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),{text:"Successfully zoomed to world extent"}}async function Bt(e,t){let{mapView:r}=$(t);return await Qt(r)}var Ut=I.object({}),Pi=h(Bt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Ut});async function Kt(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return{text:"Successfully zoomed to home extent"}}async function Wt(e,t){let{mapView:r}=$(t);return await Kt(r)}var Ht=i.object({}),Gi=h(Wt,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:Ht});async function Jt(e,t){await t.when();let r=t.map?.allLayers.find(a=>a.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),{text:`Could not find layer for: ${e}`};let o;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?o=t.map.diagramNodesExtent:o=r.fullExtent,o?(await t.goTo(o),r.visible=!0,{text:`Successfully zoomed to: ${r.title??""}`}):{text:"Layer has no defined extent. Cannot zoom to layer."}}async function Zt({layerId:e},t){let{mapView:r}=$(t);return await Jt(e,r)}var Yt=I.object({layerId:I.string().describe("The id of the layer to navigate to")}),Vi=h(Zt,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:Yt});async function Xt(e,t){return await t.goTo({scale:e}),{text:`Successfully zoomed to: ${e}`}}async function er({scale:e},t){let{mapView:r}=$(t);return await Xt(e,r)}var tr=i.object({scale:i.number().describe("The map scale of the view to go to.")}),Qi=h(er,{name:"goToScale",description:"Go to the specified view scale.",schema:tr});async function rr(e,t,r){let o={target:new Re({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(o.zoom=r.zoom),r?.scale!==void 0&&(o.scale=r.scale),await t.goTo(o),{text:`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}}async function or({center:e,zoom:t,scale:r},o){let{mapView:a}=$(o);return await rr(e,a,{zoom:t,scale:r})}var ar=i.object({center:i.object({longitude:i.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:i.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:i.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:i.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),Bi=h(or,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:ar});async function nr(e,t){return await t.goTo({zoom:e}),{text:`Successfully zoomed to: ${e}`}}async function ir({zoom:e},t){let{mapView:r}=$(t);return await nr(e,r)}var sr=i.object({zoom:i.number().min(1).max(20).describe("The zoom level of the view to go to.")}),Ui=h(ir,{name:"goToZoom",description:'Go to the specified zoom level. If input is generic (e.g. "zoom in", then only zoom to the next appropriate level - increase level for zooming in and decrease for zooming out.).',schema:sr}),Ae=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./KMQ3SP4I.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_map_context.md":()=>import("./5QAHYX7Y.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_lucene_generation_prompt.md":()=>import("./5ZZGKP7N.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_summarize_result_prompt.md":()=>import("./AXDZBBNL.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./ZS2TZ6BF.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./LQ6R5YRN.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./X2ZDYHCG.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./ZLXN7NMF.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./F2AHA4GB.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./FX7UOGHP.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./NE7E52YR.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./6YMR4QSD.js").then(e=>e.default)});async function ne(e){let t=Object.entries(Ae).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
|
|
4
4
|
Available prompts:
|
|
5
5
|
${Object.keys(Ae).join(`
|
|
6
6
|
`)}`);return await t[1]()}var lr=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r},je=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},Ki=(e,t)=>(r,o)=>{let a=o?.configurable?.services;for(let n of e)if(!a?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r};async function cr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,s;return n?s=it({basemapTheme:await ke(o),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=st({basemapTheme:await ke(o),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:o,attributes:t.map(l=>({field:l,label:r.fields.find(u=>u.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),pieChartScheme:s}}async function ur(e){return await nt(e)}async function dr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let s=t,l=e?.allLayers.find(c=>c.id===r);if(!l)return`Could not find layer for id: ${r}`;let u={styleName:n?"chart-size":"chart",fields:o,layer:l,view:s,colorSchemeTags:a};try{let c=await cr(u),d=await ur(c);return l.renderer=d.renderer,l.visible=!0,`Chart renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(c){return`Error applying chart renderer: ${c instanceof Error?c.message:String(c)}`}}var pr=["mapView"];function x(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=pr.filter(o=>!(o in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function mr({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await dr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var hr=i.object({layerId:i.string().describe("The id of the layer to apply the chart renderer to"),fields:i.array(i.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),includeSize:i.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Wi=h(mr,{name:"chart",description:`Label: Charts
|
|
@@ -40,7 +40,7 @@ ${Object.keys(Ae).join(`
|
|
|
40
40
|
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
41
41
|
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
42
42
|
Example: Create a heatmap
|
|
43
|
-
Fields: This typically requires zero or one field of type number.`,schema:Or});function Dr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,s;return n&&(s=yt({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:o,fields:t.map(l=>({name:l})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),predominanceScheme:s}}async function
|
|
43
|
+
Fields: This typically requires zero or one field of type number.`,schema:Or});function Dr(e){let{fields:t,layer:r,view:o,styleName:a,colorSchemeTags:n}=e,s;return n&&(s=yt({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:o,fields:t.map(l=>({name:l})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:a.includes("Size"),predominanceScheme:s}}async function Pr(e){return await ft(e)}async function Gr({arcgisMap:e,arcgisMapView:t,layerId:r,fields:o,colorSchemes:a,includeSize:n}){let s=t,l=e?.allLayers.find(c=>c.id===r);if(!l)return`Could not find layer for id: ${r}`;let u={styleName:n?"predominance-size":"predominance",fields:o,layer:l,view:s,colorSchemeTags:a};try{let c=Dr(u),d=await Pr(c);return l.renderer=d.renderer,l.visible=!0,`Predominance renderer applied to layer: ${l.title??l.id} using fields ${o.join(", ")}`}catch(c){return`Error applying predominance renderer: ${c instanceof Error?c.message:String(c)}`}}async function Vr({layerId:e,fields:t,colorSchemes:r,includeSize:o},a){let{mapView:n}=x(a);return await S({type:"show-legend",data:{layerIds:[e]}},a),await Gr({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:o})}var Qr=i.object({layerId:i.string().describe("The id of the layer to apply the predominance renderer to"),fields:i.array(i.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:i.array(i.string()).optional().describe("Optional color scheme tags to use"),includeSize:i.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),es=h(Vr,{name:"predominance",description:`Label: Predominant category
|
|
44
44
|
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
45
45
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
46
46
|
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
@@ -72,7 +72,7 @@ Fields: This typically requires zero or one field of type number.`,schema:Or});f
|
|
|
72
72
|
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
73
73
|
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
74
74
|
Example: Color each feature based on the region it belongs to
|
|
75
|
-
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:uo}),ns=g.Root({...L(),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),is=g.Root({...L(),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g(),dataExplorationMessages:g({reducer:j,default:()=>[]})}),po=["mapView"];function A(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=po.filter(o=>!(o in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var mo=e=>{let t=e.map?.allLayers.filter(o=>o.type==="feature"),r=0;return t?.forEach(o=>{let a=o;a.featureEffect&&(a.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},ho=async(e,t)=>{let{mapView:r}=A(t);return mo(r)},fo=h(ho,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:i.object({})}),yo=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},go=async(e,t)=>{let{mapView:r}=A(t);return await yo(r)},wo=h(go,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:i.object({})});function H(e){return"point"in e&&e.point!==void 0}function D(e){return"layerId"in e&&e.layerId!==void 0}var Z=async(e,t)=>{if(H(e)){let{point:r}=e;return{geometry:new Re({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(D(e)){let r=t.map?.allLayers.find(a=>a.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let o=r.title??r.id;try{let a=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${e.where}`};let n;if(a.features.length===1){let s=a.features[0].geometry;if(!s)return{error:"The geometry of the first feature is undefined or null."};n=s}else{let s=a.features.map(u=>u.geometry),l=qe.executeMany(s);if(!l)return{error:"Failed to create a combined geometry."};n=l}return n.spatialReference||(n.spatialReference=t.spatialReference),{geometry:n}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},bo=async(e,t,r,o,a,n)=>{let s=e.map?.allLayers.find(u=>u.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let l=s.createQuery();l.where=r??"1=1",o&&(l.geometry=o,l.spatialRelationship="intersects",a&&(l.distance=a),n&&(l.units=n));try{let{extent:u,count:c}=await s.queryExtent(l);return!u||c===0?{success:!1,error:`No features found for filter (where: ${l.where}${o?", spatial filter used":""})`}:(await e.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},vo=async(e,t,r,o,a,n)=>{let s=t.map?.allLayers.find(p=>p.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let l;if(a){let p=await Z(a,t);if("error"in p)return p.error;l=p.geometry}if(s.featureEffect=null,s.featureEffect=new xt({filter:new _e({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:l,spatialRelationship:"intersects",distance:a?.distance,units:a?.units}),includedEffect:r,excludedEffect:o}),s.visible=!0,n)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let u=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await bo(t,e.layerId,u,l,a?.distance,a?.units),d=s.title??e.layerId;return c.success?`Applied feature effects to target layer "${s.title??e.layerId}"${a&&"layerId"in a?` using geometry from layer "${a.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${c.error}`},To=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],N=i.enum(To),So=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:s}=A(n);return await vo(e,s,o,a,t,r)},xo=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:N.optional().describe("The units for the distance buffer.")}),Eo=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:i.number().optional().describe("Optional buffer distance around the point."),units:N.optional().describe("The units for the distance buffer.")}),Io=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer on which to set a feature effect."),where:i.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:i.array(i.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:i.union([xo,Eo]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:i.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:i.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:i.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),$o=h(So,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Io}),ie=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},No=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,ko=e=>{if(typeof e=="string"&&e)return e;let t=ie(e);return t?t.toISOString().slice(0,10):null},ss=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),o=(Math.abs(e)%60).toString().padStart(2,"0"),a=`${t}${r}:${o}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:a}},Fo=(e,t,r)=>{let o=t?.toLowerCase();if(o==="date-only"){let n=ko(e);return n?Et(n,U("short-date")):e}if(o==="time-only"){if(typeof e=="string"&&e)return It(e,U("long-time"));let n=ie(e);return n?Fe(n,{...U("long-time"),timeZone:"UTC"}):e}let a=ie(e);return a?Fe(a,{...U("short-date-short-time"),timeZone:No(r)}):e},Le=(e,t,r)=>{if(e&&typeof e!="function"){let o="getField"in r&&r.getField?.(e),a=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(a?.type==="coded-value"){let n=a.codedValues.find(s=>s.code===t);return n?n.name:null}}return null},Mo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Ao=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Co=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},Ro=(e,t,r)=>{let o=Ao(e);if(!o)return e;let a={};t.dateStyle?a.dateStyle=t.dateStyle:(t.year&&(a.year=t.year),t.month&&(a.month=t.month)),t.timeStyle&&(a.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?a.hour12=!0:t.timeStyle&&t.hour12==="never"&&(a.hour12=!1),a.timeZone=Mo(r);try{return new Intl.DateTimeFormat(void 0,a).format(o)}catch{return e}},Oe=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,De=(e,t,r,o,a)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?Co(r,n):n?.type==="date-time"?Ro(r,n,a):Fo(r,o,a)},_o=(e,t,r,o)=>{let a=e.fieldsIndex?.get(t),n=Le(t,r,e)??r;return De(e,t,n,a?.type,o)},qo=(e,t)=>Oe(e,t),Ge=(e,t,r)=>{let o=e.objectIdField,a=t.features.map(s=>s.attributes[o]),n=t.features.map(s=>{let l=s.attributes,u={};return e.fields.forEach(c=>{if(!Object.hasOwn(l,c.name))return;let d=l[c.name];if(c.name===o){u[c.name]=d;return}let p=Le(c.name,d,e)??d,m=Oe(e,c.name);u[m]=De(e,c.name,p,c.type,r)}),u});return{objectIds:a,attributes:n}},zo=(e,t,r)=>{let o=e.createQuery();return o.outFields=[t],o.where=r||"1=1",o.num=1,o},jo=async(e,t,r,o)=>{let a=o.map?.allLayers.find(d=>d.id===e),n=zo(a,t,r.where),s=(await a.queryFeatures(n)).features[0],l=s?s.attributes[t]:null,u=_o(a,t,l,o.timeZone),c=qo(a,t);return{tool:"getAttribute",layerName:a.title??e,summary:`${c} = ${u}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:u,where:r.where}}};async function Lo({layerId:e,fieldName:t,query:r},o){let{mapView:a}=A(o),n=await jo(e,t,r,a);return JSON.stringify(n,null,2)}var Oo=i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:i.string().describe("The name of the field/attribute from which to get a field value."),query:i.object({where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Do=h(Lo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Oo}),me=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function J(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Go=async e=>{let{targetLayer:t,fieldName:r,statisticType:o,mapView:a,layersAndFieldsRegistry:n,geometryFilter:s}=e,l=a.map?.allLayers.find(v=>v.id===t.layerId);if(!l)throw new Error(`Layer '${t.layerId}' not found.`);let u=await a.whenLayerView(l),c=n.get(t.layerId)?.fieldRegistry.get(r),d=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let p,m;if(s){let v=await Z(s,a);if("error"in v)throw new Error(v.error);if(!v.geometry)throw D(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");if(D(s)){let E=a.map?.allLayers.find(k=>k.id===s.layerId);p={geometryLayerName:E?.title??E?.id,geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}}else H(s)&&(p={point:s.point,distance:s.distance,units:s.units,applied:!0});m=new _e({geometry:v.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let y=me(u,[r],!1),b=null,f=null,w=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let v={layer:l,useFeaturesInView:y,view:y?a:void 0,field:r,sqlWhere:J(l.definitionExpression,t.where),...m&&{filter:m},outStatisticTypes:{include:[o]}};b=await $t(v);let E=["string","small-integer","integer"],k=c.domain?.type==="coded-value"?c.domain:null;(E.includes(c.type)||k)&&(f=(await Nt({layer:l,useFeaturesInView:y,view:y?a:void 0,field:r,sqlWhere:J(l.definitionExpression,t.where),...m&&{filter:m}})).uniqueValueInfos.sort((R,He)=>He.count-R.count).slice(0,w)),f&&c.domain?.type==="coded-value"&&(f=f.map(R=>({...R,value:k?k.getName(R.value)??R.value:R.value})))}catch(v){console.error("Statistics error:",v)}return{tool:"getStatistics",layerName:l.title??t.layerId,summary:`${o} = ${typeof b?.[o]=="number"?b[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:b?.[o]??null,summaryStatistics:b,uniqueValues:f,where:t.where,spatialFilterInfo:p}}};async function Po({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:o},a){let n=je(a,"layersAndFieldsRegistry"),{mapView:s}=A(a),l=await Go({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:o});return JSON.stringify(l,null,2)}var Vo=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:N.optional().describe("The units for the distance buffer.")}),Qo=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:i.number().optional().describe("Optional buffer distance around the point."),units:N.optional().describe("The units for the distance buffer.")}),Bo=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:i.union([Vo,Qo]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:i.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:i.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Uo=h(Po,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
75
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:uo}),ns=g.Root({...L(),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),is=g.Root({...L(),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g(),dataExplorationMessages:g({reducer:j,default:()=>[]})}),po=["mapView"];function A(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=po.filter(o=>!(o in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var mo=e=>{let t=e.map?.allLayers.filter(o=>o.type==="feature"),r=0;return t?.forEach(o=>{let a=o;a.featureEffect&&(a.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},ho=async(e,t)=>{let{mapView:r}=A(t);return mo(r)},fo=h(ho,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:i.object({})}),yo=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let o=r;o.featureEffect&&(o.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},go=async(e,t)=>{let{mapView:r}=A(t);return await yo(r)},wo=h(go,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:i.object({})});function H(e){return"point"in e&&e.point!==void 0}function D(e){return"layerId"in e&&e.layerId!==void 0}var Z=async(e,t)=>{if(H(e)){let{point:r}=e;return{geometry:new Re({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(D(e)){let r=t.map?.allLayers.find(a=>a.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let o=r.title??r.id;try{let a=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer "${o}" with the specified where clause: ${e.where}`};let n;if(a.features.length===1){let s=a.features[0].geometry;if(!s)return{error:"The geometry of the first feature is undefined or null."};n=s}else{let s=a.features.map(u=>u.geometry),l=qe.executeMany(s);if(!l)return{error:"Failed to create a combined geometry."};n=l}return n.spatialReference||(n.spatialReference=t.spatialReference),{geometry:n}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},bo=async(e,t,r,o,a,n)=>{let s=e.map?.allLayers.find(u=>u.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let l=s.createQuery();l.where=r??"1=1",o&&(l.geometry=o,l.spatialRelationship="intersects",a&&(l.distance=a),n&&(l.units=n));try{let{extent:u,count:c}=await s.queryExtent(l);return!u||c===0?{success:!1,error:`No features found for filter (where: ${l.where}${o?", spatial filter used":""})`}:(await e.goTo(u),{success:!0})}catch(u){return{success:!1,error:u instanceof Error?u.message:String(u)}}},vo=async(e,t,r,o,a,n)=>{let s=t.map?.allLayers.find(p=>p.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let l;if(a){let p=await Z(a,t);if("error"in p)return p.error;l=p.geometry}if(s.featureEffect=null,s.featureEffect=new xt({filter:new _e({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:l,spatialRelationship:"intersects",distance:a?.distance,units:a?.units}),includedEffect:r,excludedEffect:o}),s.visible=!0,n)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let u=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,c=await bo(t,e.layerId,u,l,a?.distance,a?.units),d=s.title??e.layerId;return c.success?`Applied feature effects to target layer "${s.title??e.layerId}"${a&&"layerId"in a?` using geometry from layer "${a.layerId}"`:""}.`:`Applied filter to "${d}" but no features matched. ${c.error}`},To=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],N=i.enum(To),So=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:o="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:s}=A(n);return await vo(e,s,o,a,t,r)},xo=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:N.optional().describe("The units for the distance buffer.")}),Eo=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:i.number().optional().describe("Optional buffer distance around the point."),units:N.optional().describe("The units for the distance buffer.")}),Io=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer on which to set a feature effect."),where:i.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:i.array(i.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:i.union([xo,Eo]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:i.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:i.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:i.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),$o=h(So,{name:"setFeatureEffect",description:"Sets a feature effect on a given layer with given filter parameters and feature effects to emphasize certain features that meet a filter requirement. If no feature effect information is provided, then use the default effect provided.",schema:Io}),ie=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},No=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,ko=e=>{if(typeof e=="string"&&e)return e;let t=ie(e);return t?t.toISOString().slice(0,10):null},ss=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),o=(Math.abs(e)%60).toString().padStart(2,"0"),a=`${t}${r}:${o}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:a}},Fo=(e,t,r)=>{let o=t?.toLowerCase();if(o==="date-only"){let n=ko(e);return n?Et(n,U("short-date")):e}if(o==="time-only"){if(typeof e=="string"&&e)return It(e,U("long-time"));let n=ie(e);return n?Fe(n,{...U("long-time"),timeZone:"UTC"}):e}let a=ie(e);return a?Fe(a,{...U("short-date-short-time"),timeZone:No(r)}):e},Le=(e,t,r)=>{if(e&&typeof e!="function"){let o="getField"in r&&r.getField?.(e),a=o&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(o.name):null;if(a?.type==="coded-value"){let n=a.codedValues.find(s=>s.code===t);return n?n.name:null}}return null},Mo=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Ao=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Co=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},Ro=(e,t,r)=>{let o=Ao(e);if(!o)return e;let a={};t.dateStyle?a.dateStyle=t.dateStyle:(t.year&&(a.year=t.year),t.month&&(a.month=t.month)),t.timeStyle&&(a.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?a.hour12=!0:t.timeStyle&&t.hour12==="never"&&(a.hour12=!1),a.timeZone=Mo(r);try{return new Intl.DateTimeFormat(void 0,a).format(o)}catch{return e}},Oe=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,De=(e,t,r,o,a)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?Co(r,n):n?.type==="date-time"?Ro(r,n,a):Fo(r,o,a)},_o=(e,t,r,o)=>{let a=e.fieldsIndex?.get(t),n=Le(t,r,e)??r;return De(e,t,n,a?.type,o)},qo=(e,t)=>Oe(e,t),Pe=(e,t,r)=>{let o=e.objectIdField,a=t.features.map(s=>s.attributes[o]),n=t.features.map(s=>{let l=s.attributes,u={};return e.fields.forEach(c=>{if(!Object.hasOwn(l,c.name))return;let d=l[c.name];if(c.name===o){u[c.name]=d;return}let p=Le(c.name,d,e)??d,m=Oe(e,c.name);u[m]=De(e,c.name,p,c.type,r)}),u});return{objectIds:a,attributes:n}},zo=(e,t,r)=>{let o=e.createQuery();return o.outFields=[t],o.where=r||"1=1",o.num=1,o},jo=async(e,t,r,o)=>{let a=o.map?.allLayers.find(d=>d.id===e),n=zo(a,t,r.where),s=(await a.queryFeatures(n)).features[0],l=s?s.attributes[t]:null,u=_o(a,t,l,o.timeZone),c=qo(a,t);return{tool:"getAttribute",layerName:a.title??e,summary:`${c} = ${u}`,details:{fieldName:t,fieldAlias:c!==t?c:void 0,value:u,where:r.where}}};async function Lo({layerId:e,fieldName:t,query:r},o){let{mapView:a}=A(o),n=await jo(e,t,r,a);return JSON.stringify(n,null,2)}var Oo=i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:i.string().describe("The name of the field/attribute from which to get a field value."),query:i.object({where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Do=h(Lo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Oo}),me=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function J(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var Po=async e=>{let{targetLayer:t,fieldName:r,statisticType:o,mapView:a,layersAndFieldsRegistry:n,geometryFilter:s}=e,l=a.map?.allLayers.find(v=>v.id===t.layerId);if(!l)throw new Error(`Layer '${t.layerId}' not found.`);let u=await a.whenLayerView(l),c=n.get(t.layerId)?.fieldRegistry.get(r),d=c?.alias;if(!c)throw new Error(`Field '${r}' not found.`);let p,m;if(s){let v=await Z(s,a);if("error"in v)throw new Error(v.error);if(!v.geometry)throw D(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");if(D(s)){let E=a.map?.allLayers.find(k=>k.id===s.layerId);p={geometryLayerName:E?.title??E?.id,geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}}else H(s)&&(p={point:s.point,distance:s.distance,units:s.units,applied:!0});m=new _e({geometry:v.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let y=me(u,[r],!1),b=null,f=null,w=10;if(c.type!=="geometry"&&c.type!=="oid"&&c.type!=="global-id")try{let v={layer:l,useFeaturesInView:y,view:y?a:void 0,field:r,sqlWhere:J(l.definitionExpression,t.where),...m&&{filter:m},outStatisticTypes:{include:[o]}};b=await $t(v);let E=["string","small-integer","integer"],k=c.domain?.type==="coded-value"?c.domain:null;(E.includes(c.type)||k)&&(f=(await Nt({layer:l,useFeaturesInView:y,view:y?a:void 0,field:r,sqlWhere:J(l.definitionExpression,t.where),...m&&{filter:m}})).uniqueValueInfos.sort((R,He)=>He.count-R.count).slice(0,w)),f&&c.domain?.type==="coded-value"&&(f=f.map(R=>({...R,value:k?k.getName(R.value)??R.value:R.value})))}catch(v){console.error("Statistics error:",v)}return{tool:"getStatistics",layerName:l.title??t.layerId,summary:`${o} = ${typeof b?.[o]=="number"?b[o]:"N/A"}`,details:{fieldName:r,fieldAlias:d,statisticType:o,statistic:b?.[o]??null,summaryStatistics:b,uniqueValues:f,where:t.where,spatialFilterInfo:p}}};async function Go({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:o},a){let n=je(a,"layersAndFieldsRegistry"),{mapView:s}=A(a),l=await Po({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:o});return JSON.stringify(l,null,2)}var Vo=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:N.optional().describe("The units for the distance buffer.")}),Qo=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:i.number().optional().describe("Optional buffer distance around the point."),units:N.optional().describe("The units for the distance buffer.")}),Bo=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:i.union([Vo,Qo]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:i.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:i.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Uo=h(Go,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
76
76
|
|
|
77
77
|
USE THIS TOOL FOR:
|
|
78
78
|
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
@@ -84,7 +84,7 @@ DO NOT USE FOR:
|
|
|
84
84
|
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
85
85
|
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
86
86
|
|
|
87
|
-
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Bo}),Ko=async(e,t,r,o,a)=>{let n=r.map?.allLayers.find(m=>m.id===e.layerId),s=await r.whenLayerView(n),l=n.title??e.layerId,u;if(o){let m=await Z(o,r);if("error"in m)return{tool:"getTopFeatures",layerName:l,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:l,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in o?o.where:"unknown criteria"}`}};u=m.geometry}else a&&(u=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,d=n.objectIdField,p=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])];try{let m;if(c){let f=new kt({where:e.where||"1=1",outFields:p,orderByFields:e.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new Ft({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});m=await n.queryTopFeatures(f)}else{let f=n.createQuery();f.where=J(n.definitionExpression,e.where||"1=1"),f.outFields=p.length?p:["*"],f.orderByFields=t.orderByFields,f.num=t.topCount,u&&(f.geometry=u,f.spatialRelationship="intersects"),o?.distance&&(f.distance=o.distance),o?.units&&(f.units=o.units),f.outSpatialReference=r.spatialReference;let w=me(s,e.outFields,a??!1);try{m=w?await s.queryFeatures(f):await n.queryFeatures(f)}catch(v){console.warn("Client-side query failed, falling back to server:",v),m=await n.queryFeatures(f)}}let y=m.features.map(f=>f.attributes[d]),{attributes:b}=
|
|
87
|
+
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:Bo}),Ko=async(e,t,r,o,a)=>{let n=r.map?.allLayers.find(m=>m.id===e.layerId),s=await r.whenLayerView(n),l=n.title??e.layerId,u;if(o){let m=await Z(o,r);if("error"in m)return{tool:"getTopFeatures",layerName:l,summary:"Geometry lookup failed",details:{error:m.error}};if(!m.geometry)return{tool:"getTopFeatures",layerName:l,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in o?o.where:"unknown criteria"}`}};u=m.geometry}else a&&(u=r.extent.clone());let c=t.groupByFields&&t.groupByFields.length>0,d=n.objectIdField,p=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])];try{let m;if(c){let f=new kt({where:e.where||"1=1",outFields:p,orderByFields:e.orderByFields,geometry:u,spatialRelationship:u?"intersects":void 0,distance:o?.distance,units:o?.units,topFilter:new Ft({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});m=await n.queryTopFeatures(f)}else{let f=n.createQuery();f.where=J(n.definitionExpression,e.where||"1=1"),f.outFields=p.length?p:["*"],f.orderByFields=t.orderByFields,f.num=t.topCount,u&&(f.geometry=u,f.spatialRelationship="intersects"),o?.distance&&(f.distance=o.distance),o?.units&&(f.units=o.units),f.outSpatialReference=r.spatialReference;let w=me(s,e.outFields,a??!1);try{m=w?await s.queryFeatures(f):await n.queryFeatures(f)}catch(v){console.warn("Client-side query failed, falling back to server:",v),m=await n.queryFeatures(f)}}let y=m.features.map(f=>f.attributes[d]),{attributes:b}=Pe(n,m,r.timeZone);return{tool:"getTopFeatures",layerName:l,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:b,objectIds:y,objectIdField:d,where:e.where,orderByFields:t.orderByFields,...c&&{groupByFields:t.groupByFields}}}}catch(m){return{tool:"getTopFeatures",layerName:l,summary:"Query failed",details:{error:m instanceof Error?m.message:String(m)}}}},Wo=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:o},a)=>{let{mapView:n}=A(a),s=await Ko(e,t,n,r,o);return JSON.stringify(s,null,2)},Ho=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:N.optional().describe("The units for the distance buffer.")}),Jo=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:i.number().optional().describe("Optional buffer distance around the point."),units:N.optional().describe("The units for the distance buffer.")}),Zo=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:i.array(i.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:i.array(i.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:i.union([Ho,Jo]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:i.object({topCount:i.number().describe("Number of top features to return per group."),orderByFields:i.array(i.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:i.array(i.string().describe("Field(s) to group results by. Returns top N per group."))}).required(),useCurrentExtent:i.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at'. Default is false (queries entire layer).")}),Yo=h(Wo,{name:"getTopFeatures",description:'Returns top N features ranked by an existing field value. Use for "highest", "lowest", "top N" questions where ranking is based on a field that already exists in the data (e.g., population, value, date, depth). orderByFields must be actual field names with ASC/DESC. Do NOT use aggregate functions like COUNT(), SUM(), AVG() - those require getStatistics.',schema:Zo}),ae=25,Xo=async(e,t,r,o)=>{let a=t.map?.allLayers.find(f=>f.id===e.layerId),n=await t.whenLayerView(a),s=a.title??e.layerId,l;if(r){let f=await Z(r,t);if("error"in f){let w={error:f.error};if(D(r)){let v=t.map?.allLayers.find(E=>E.id===r.layerId);w.geometryLayerName=v?.title??v?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else H(r)&&(w.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:w}}if(!f.geometry){let w={};if(D(r)){let v=t.map?.allLayers.find(E=>E.id===r.layerId);w.error=`No features found matching: ${r.where}`,w.geometryLayerName=v?.title??v?.id,w.geometryLayerId=r.layerId,w.geometryWhere=r.where}else H(r)&&(w.error="Failed to create point geometry",w.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:w}}l=f.geometry}else o&&(l=t.extent.clone());let u=me(n,e.outFields,o??!1),c=a.objectIdField,d=a.createQuery();d.where=J(a.definitionExpression,e.where||"1=1"),d.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,c])],d.orderByFields=e.orderByFields,l&&(d.geometry=l,d.spatialRelationship="intersects"),r?.distance&&(d.distance=r.distance),r?.units&&(d.units=r.units),d.outSpatialReference=t.spatialReference;let p,m;try{p=u?await n.queryFeatureCount(d):await a.queryFeatureCount(d),p>0&&p<=ae&&(m=u?await n.queryFeatures(d):await a.queryFeatures(d))}catch(f){console.warn("Client-side query failed, falling back to server:",f),p=await a.queryFeatureCount(d),p>0&&p<=ae&&(m=await a.queryFeatures(d))}let{objectIds:y,attributes:b}=m?Pe(a,m,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:s,summary:`${p} features found`,details:{totalCount:p,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...y&&{objectIds:y,objectIdField:c},...b&&{attributes:b},...p>ae&&{note:`${p} features found.`}}}};async function ea({targetLayer:e,geometryFilter:t,useCurrentExtent:r},o){let{mapView:a}=A(o),n=await Xo(e,a,t,r);return JSON.stringify(n,null,2)}var ta=i.object({layerId:i.string().describe("The layerId of the layer containing the geometry by which to filter."),where:i.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:i.number().optional().describe("The buffer distance around the geometry."),units:N.optional().describe("The units for the distance buffer.")}),ra=i.object({point:i.object({x:i.number().describe("X coordinate (longitude) from navigation result"),y:i.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:i.object({wkid:i.number().describe("Spatial reference WKID (e.g., 4326 for WGS84)")}).optional().describe("Spatial reference. Defaults to map's spatial reference if not provided.")}).describe("Point coordinates from a previous navigation/geocoding result"),distance:i.number().optional().describe("Optional buffer distance around the point."),units:N.optional().describe("The units for the distance buffer.")}),oa=i.object({targetLayer:i.object({layerId:i.string().describe("The layerId of the layer containing the field from which to get a value."),where:i.string().describe("SQL-92 where clause. IMPORTANT: When using geometryFilter.point for point-in-polygon queries, set this to '1=1' to return all features that intersect the point. Only add attribute filters if the user specifically requests them in addition to the spatial query."),orderByFields:i.array(i.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:i.array(i.string().describe('The fields to include in the output that will be presented to the user. This should include identifying information about the resulting features, like a name or id, along with the values desired in the output. If unsure, choose all fields ("*").').default("*"))}),geometryFilter:i.union([ta,ra]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),useCurrentExtent:i.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),aa=h(ea,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
88
88
|
|
|
89
89
|
USE THIS TOOL FOR:
|
|
90
90
|
- "Show / display / list features where..." \u2014 finding and listing features
|
|
@@ -98,8 +98,8 @@ This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema
|
|
|
98
98
|
`)):"Query executed."}}var us=g.Root({...L(),helpInternalState:g({reducer:O,default:()=>({toolCallMessage:void 0})})}),sa=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(s=>s.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let o=Array.from(r.fieldRegistry.values()),a=o.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
|
|
99
99
|
`);return`**${r.layerItem.title}** has ${o.length} field(s):
|
|
100
100
|
|
|
101
|
-
${a}`},la=async({layerTitle:e},t)=>{let r=je(t,"layersAndFieldsRegistry");return sa(r,e)},ds=h(la,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:i.object({layerTitle:i.string().describe("The title or partial title of the layer to list fields for.")})}),ps=g.Root({...L(),intent:g({reducer:(e,t)=>t}),arcgisKnowledgeMessages:g({reducer:j,default:()=>[]}),arcgisKnowledgeToolResult:g({reducer:(e,t)=>t,default:()=>null})}),K={conversationId:""};function he(e){let t=e.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!t||t?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function C(e){return!!e?.map&&!("activeLinkChartLayer"in e.map)}async function Y(e){!e||C(e)||!e.map?.diagramNodesExtent||await e.goTo(e.map.diagramNodesExtent)}function X(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in t))throw new Error("View context missing");let r=t.view;return r.map&&!("activeLinkChartLayer"in r.map)&&he(r),{view:r}}function ms(e){let t=e?.configurable?.context;if(
|
|
102
|
-
Relationship Types: ${o}.`}},
|
|
101
|
+
${a}`},la=async({layerTitle:e},t)=>{let r=je(t,"layersAndFieldsRegistry");return sa(r,e)},ds=h(la,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use ONLY when the user explicitly asks to see fields, columns, or attributes of a specific named layer. Do NOT call this tool for general help questions, capability overviews, or layer listing.",schema:i.object({layerTitle:i.string().describe("The title or partial title of the layer to list fields for.")})}),ps=g.Root({...L(),intent:g({reducer:(e,t)=>t}),arcgisKnowledgeMessages:g({reducer:j,default:()=>[]}),arcgisKnowledgeToolResult:g({reducer:(e,t)=>t,default:()=>null})}),K={conversationId:""};function he(e){let t=e.map?.allLayers.filter(r=>r.type==="knowledge-graph");if(!t||t?.length!==1)throw new Error("The Knowledge Agent currently only supports maps with exactly one Knowledge Graph Layer.")}function C(e){return!!e?.map&&!("activeLinkChartLayer"in e.map)}async function Y(e){!e||C(e)||!e.map?.diagramNodesExtent||await e.goTo(e.map.diagramNodesExtent)}function X(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if(!("view"in t))throw new Error("View context missing");let r=t.view;return r.map&&!("activeLinkChartLayer"in r.map)&&he(r),{view:r}}function ms(e){let t=e?.configurable?.context;if(Ge(e)==="knowledgeGraph")return"knowledgeGraph";let r=t.view;return C(r)?(he(r),"map"):"linkChart"}async function G(e){let t=e?.configurable?.context;if(Ge(e)==="knowledgeGraph")return t;{let r=t.view.map;if(r&&"activeLinkChartLayer"in r){let o=r.knowledgeGraph?.url;if(!o)throw new Error("Knowledge graph url missing from link chart.");return{knowledgeGraph:await Me(o)}}else{he(t.view);let o=(t.view.map?.allLayers.find(a=>a.type==="knowledge-graph")).url;if(!o)throw new Error("Knowledge graph url missing from map.");return{knowledgeGraph:await Me(o)}}}}function Ge(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");if("knowledgeGraph"in t&&"view"in t)throw new Error("Knowledge Graph context should only have a view or knowledgeGraph, but never both.");if("knowledgeGraph"in t)return"knowledgeGraph";if("view"in t)return"view";throw new Error("ArcgisKnowledgeAgent context must have either a view or knowledgeGraph property.")}var se=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=le.fromDataModel(t)}},le=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let o of t.entityTypes)r.entityTypes.push(P.fromEntityType(o));for(let o of t.relationshipTypes)r.relationshipTypes.push(ce.fromRelationshipType(o));return r.identifierInfo={mappingInfo:{identifierMapsTo:ca(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}static getDataModelTypesSummary(t){let r=t.entityTypes.map(a=>a.name).join(", "),o=t.relationshipTypes.map(a=>a.name).join(", ");return`Entity Types: ${r}.
|
|
102
|
+
Relationship Types: ${o}.`}},P=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=ua(t.role);for(let o of t.properties){let a={name:o.name,alias:o.alias?o.alias:void 0,fieldType:o.fieldType,role:da(o.role),geometryDef:o.fieldType==="esriFieldTypeGeometry"?{geometryType:o.geometryType??"esriGeometryAny",hasM:o.hasM?o.hasM:void 0,hasZ:o.hasZ?o.hasZ:void 0}:void 0};r.properties.push(a)}return r}},ce=class extends P{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=P.fromEntityType(t);r.observedEndPoints=[];for(let o of t.endPoints)r.observedEndPoints.push({originEntityType:o.originEntityType,destinationEntityType:o.destinationEntityType});return r}},ca=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},ua=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function da(e){switch(e){case"esriGraphPropertyRegular":return"Regular";case"esriGraphPropertyDocumentName":return"Document_Name";case"esriGraphPropertyDocumentTitle":return"Document_Title";case"esriGraphPropertyDocumentUrl":return"Document_Url";case"esriGraphPropertyDocumentText":return"Document_Text";case"esriGraphPropertyDocumentKeywords":return"Document_Keywords";case"esriGraphPropertyDocumentContentType":return"Document_ContentType";case"esriGraphPropertyDocumentMetadata":return"Document_Metadata";case"esriGraphPropertyDocumentFileExtension":return"Document_FileExtension";case"esriGraphPropertyProvenanceInstanceId":return"Provenance_InstanceId";case"esriGraphPropertyProvenanceSourceType":return"Provenance_SourceType";case"esriGraphPropertyProvenanceSourceName":return"Provenance_SourceName";case"esriGraphPropertyProvenanceSource":return"Provenance_Source";case"esriGraphPropertyProvenanceComment":return"Provenance_Comment";case"esriGraphPropertyProvenanceTypeName":return"Provenance_TypeName";case"esriGraphPropertyProvenancePropertyName":return"Provenance_PropertyName";default:return"Regular"}}function pa(e,t){return t?`${e}
|
|
103
103
|
|
|
104
104
|
Your previous attempt to generate a cypher query failed. See the details below and generate a new cypher query that avoids this error.
|
|
105
105
|
|
|
@@ -115,7 +115,7 @@ ${l}
|
|
|
115
115
|
Explanation: ${u}`):(await n?.map?.allLayers.find(p=>p.type==="knowledge-graph")?.addRecords(d),`Map updated successfully. Cypher Query used:
|
|
116
116
|
${l}
|
|
117
117
|
|
|
118
|
-
Explanation: ${u}`)}var Be="addRecords",xa=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Ea=async({prompt:e},t)=>{let{knowledgeGraph:r}=await
|
|
118
|
+
Explanation: ${u}`)}var Be="addRecords",xa=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Ea=async({prompt:e},t)=>{let{knowledgeGraph:r}=await G(t),o=X(t),{view:a}=o,n=M.getDefault().helperServices,s=e;if(C(a)){let u=a.map,{allNamedTypesFullyDynamic:c,idTypePairs:d,dynamicTypes:p}=Ta(u),m=await ne("arcgis_knowledge_current_map_context");if(s=`${e}
|
|
119
119
|
|
|
120
120
|
${m}${JSON.stringify(d)} and all entities or relationships with the the following typeNames in the array: ${JSON.stringify(p)}`,c)throw new Error("No records have been added to the map because all data in the knowledge graph is contained in the map.")}else{let u=a.map,c=await ne("arcgis_knowledge_current_lc_context"),d=va(u,r);s=`${e}
|
|
121
121
|
|
|
@@ -125,11 +125,11 @@ ${l}
|
|
|
125
125
|
Explanation: ${u}`}):(await Y(o),{type:"success",message:`Link chart created successfully. Cypher Query used to create the link chart:
|
|
126
126
|
${l}
|
|
127
127
|
|
|
128
|
-
Explanation: ${u}`})}catch(c){let d=c instanceof Error?c.message:String(c);if(s>=F)throw new Error(`Failed to create link chart after ${F} attempts. Last error: ${d}`);n={failedGraphQuery:l,executionError:d,attemptCount:s},await T({text:`Attempt ${s} to create link chart failed with error: ${d}. Retrying ...`},a)}}throw new Error(`Failed to create link chart after ${F} attempts.`)}var W="createLinkChart",Ca=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Ra=async({prompt:e},t)=>{let{knowledgeGraph:r}=await
|
|
128
|
+
Explanation: ${u}`})}catch(c){let d=c instanceof Error?c.message:String(c);if(s>=F)throw new Error(`Failed to create link chart after ${F} attempts. Last error: ${d}`);n={failedGraphQuery:l,executionError:d,attemptCount:s},await T({text:`Attempt ${s} to create link chart failed with error: ${d}. Retrying ...`},a)}}throw new Error(`Failed to create link chart after ${F} attempts.`)}var W="createLinkChart",Ca=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Ra=async({prompt:e},t)=>{let{knowledgeGraph:r}=await G(t),{view:o}=X(t);if(C(o))return{toolName:W,status:"error",errorMessage:"The createLinkChart tool can only be used with a LinkChartView.",error:new Error};{let a=M.getDefault().helperServices,n=await Aa(e,r,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,o,t);return n.type==="error"?{toolName:W,status:"error",errorMessage:n.message,error:new Error}:{toolName:W,status:"success",summary:n.message}}},gs=h(Ra,{name:W,description:"Creates a new link chart visualization from an inquiry into the knowledge graph data. The inquiry will retrieve data from the graph database that will serve as the basis for the new link chart. The user should have explicitly requested the creation of a new link chart from their prompt.",schema:Ca}),Ue="queryGraphData",_a=i.object({prompt:i.string().describe(`The user's inquiry into the knowledge graph, from which a cypher query will be generated and executed to answer the inquiry. IMPORTANT:
|
|
129
129
|
|
|
130
130
|
REQUEST LIMIT: If the user does not specifically request for no limits or an explicit limit to be placed on the query, or the number of rows will not be limited by e.g. the number of entity or relationship types in the graph, ensure that the generated query has a reasonable row limit (e.g. 10 rows).
|
|
131
131
|
|
|
132
|
-
DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),qa=async({prompt:e},t)=>{let{knowledgeGraph:r}=await
|
|
132
|
+
DESCRIPTIVE COLUMN NAMES: If the user's prompt does not explicitly request for specific column names in the result, ensure that the generated query has descriptive column names (using AS statements) to make the results easier to understand when displayed in a table format.`)}),qa=async({prompt:e},t)=>{let{knowledgeGraph:r}=await G(t),o=M.getDefault().helperServices,a=await Qe({prompt:e,kg:r,graphQueryServiceUrl:`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,targetStructure:new Array,targetStructureReducer:(p,m)=>(p.push(m),p),requestOptions:{signal:t?.signal,timeout:t?.timeout},config:t});if(a.type!=="success"){let p=a.type==="generation-error"?a.errorMessage:`${a.errorMessage} Cypher query: ${a.graphQuery}`;throw new Error(`Failed to query the knowledge graph. ${p}`)}let{graphQuery:n,processedResult:s,resultHeader:l}=a,u=l.headerKeys;for(let p of s)for(let m of p)_(m,y=>Ve(y));let c=50,d=s.slice(0,c).map(p=>JSON.stringify(p));return{toolName:Ue,status:"success",summary:`To answer the inquiry, the following cypher query was executed against the knowledge graph:
|
|
133
133
|
|
|
134
134
|
\`\`\`cypher
|
|
135
135
|
${n}
|
|
@@ -146,13 +146,13 @@ ${d.length>c?`Showing top ${c} results:
|
|
|
146
146
|
|
|
147
147
|
`}${d.join(`
|
|
148
148
|
`)}
|
|
149
|
-
`,details:{generatedQuery:n,resultHeader:l,queryResults:s}}},ws=h(qa,{name:Ue,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:_a}),Ke="generateCypher",za=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),ja=async({prompt:e},t)=>{let{knowledgeGraph:r}=await
|
|
149
|
+
`,details:{generatedQuery:n,resultHeader:l,queryResults:s}}},ws=h(qa,{name:Ue,description:"Allows users to explore the data in their knowledge graph via cypher query. Generates and executes a cypher query based on the user's inquiry into the knowledge graph, and displays the results in the chat pane without modifying the user's link chart if any. Use this tool when the user is asking an exploratory question about their data as a whole that can be answered via cypher query, for example 'What are the top 5 suppliers by total parts cost?' or 'How many employees do we have in each department?'.",schema:_a}),Ke="generateCypher",za=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),ja=async({prompt:e},t)=>{let{knowledgeGraph:r}=await G(t),o=M.getDefault().helperServices,a=await ma(e,r.dataModel,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,t);return{toolName:Ke,status:"success",summary:a}},bs=h(ja,{name:Ke,description:"Generates an Open Cypher query based on the user's prompt which represents an inquiry into the data of the knowledge service and its graph database, attempting to filter based on certain conditions and traverse specified relationships. The generated query should be syntactically correct and optimized for performance.",schema:za}),La=e=>{let t=e.dataModel,r=new Map;for(let l of t.searchIndexes)if(l.supportedCategory!=="esriTypeMetaEntityProvenance")for(let[u,c]of l.searchProperties.entries()){let d=r.get(u)??new Set;c.propertyNames.forEach(p=>d.add(p)),r.set(u,d)}let o=t.entityTypes.filter(l=>r.has(l.name)),a=t.relationshipTypes.filter(l=>r.has(l.name)),n=`Entity Types:
|
|
150
150
|
${o.map(({name:l})=>`${l}: [${Array.from(r.get(l)??[]).join(", ")}]`).join(`
|
|
151
151
|
`)}`,s=`Relationship Types:
|
|
152
152
|
${a.map(({name:l})=>`${l}: [${Array.from(r.get(l)??[]).join(", ")}]`).join(`
|
|
153
153
|
`)}`;return`${n}
|
|
154
154
|
|
|
155
|
-
${s}`};async function Oa(e,t){let r=await ne("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:e,dataModelForSearch:La(t)},a=i.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),n=i.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),s=i.array(i.enum(t.dataModel.entityTypes.map(u=>u.name).concat(t.dataModel.relationshipTypes.map(u=>u.name)))).min(1),l=i.object({query:i.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:s.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:a,resultLimit:n});return await Te({promptText:r,inputVariables:o,schema:l})}var We="searchGraphData",Da=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),
|
|
155
|
+
${s}`};async function Oa(e,t){let r=await ne("arcgis_knowledge_lucene_generation_prompt"),o={inquiry:e,dataModelForSearch:La(t)},a=i.enum(["entity","relationship","both"]).describe("The graph element category to search against - entity, relationship, or both"),n=i.number().int().positive().nullable().describe("The maximum number of search results to return. Default to 10 if not specified by the user, or set to null if the user specifically requests no limits or all results."),s=i.array(i.enum(t.dataModel.entityTypes.map(u=>u.name).concat(t.dataModel.relationshipTypes.map(u=>u.name)))).min(1),l=i.object({query:i.string().describe("A lucene syntax query string to be executed against the knowledge graph search API"),typeFilters:s.nullable().describe("Nullable list of entity or relationship types from the graph to limit the search to. If set to null, search will execute against all named types with indexed properties in the graph"),typeCategoryFilter:a,resultLimit:n});return await Te({promptText:r,inputVariables:o,schema:l})}var We="searchGraphData",Da=i.object({prompt:i.string().describe("The user's inquiry into the knowledge graph, from which a lucene search query will be generated and executed against the graph to return relevant results.")}),Pa=async({prompt:e},t)=>{let{knowledgeGraph:r}=await G(t);await T({text:"Generating search query for the user inquiry"},t);let o=await Oa(e,r);await T({text:"Executing graph search with generated search query"},t);let a=await fa({kg:r,searchQuery:o.query,typeCategoryFilter:o.typeCategoryFilter,namedTypesFilter:o.typeFilters,searchResultLimit:o.resultLimit,requestOptions:{signal:t?.signal,timeout:t?.timeout}});if(a.type!=="success")throw new Error(`Graph search failed with error: ${a.type==="error"?a.errorMessage:"aborted"}`);for(let l of a.results)_(l,u=>Ve(u));let n=10,s=a.results.slice(0,n);return{toolName:We,status:"success",summary:`To answer the query, the following lucene query was generated and executed:
|
|
156
156
|
Query: ${o.query}
|
|
157
157
|
Type Category Filter: ${o.typeCategoryFilter}
|
|
158
158
|
Named Type Filters: ${o.typeFilters?o.typeFilters.join(", "):"None"}
|
|
@@ -163,4 +163,4 @@ ${s}`};async function Oa(e,t){let r=await ne("arcgis_knowledge_lucene_generation
|
|
|
163
163
|
${a.results.length>n?`Showing top ${n} results:
|
|
164
164
|
|
|
165
165
|
`:""}${s.map(l=>JSON.stringify(l)).join(`
|
|
166
|
-
`)}`,details:{generatedQuery:o,searchResults:{...a}}}},vs=h(
|
|
166
|
+
`)}`,details:{generatedQuery:o,searchResults:{...a}}}},vs=h(Pa,{name:We,description:"Allows users to search the knowledge graph for text matching their inquiry, using lucene search syntax, against indexed string properties defined on their entities and relationships. Use this tool when the user asks a question about their knowledge graph data as a whole, that could be answered via lucene text search of properties stored on graph elements, e.g requiring fuzzy matching. Otherwise if the inquiry is looking for connected records (e.g. paths), data aggregations, etc explore the data via the queryGraphData tool.",schema:Da});return{a:B,b:ji,c:$,d:Li,e:Oi,f:Di,g:Pi,h:Gi,i:Vi,j:Qi,k:Bi,l:Ui,m:ne,n:lr,o:je,p:Ki,q:Wi,r:Hi,s:Ji,t:Zi,u:Yi,v:Xi,w:es,x:ts,y:rs,z:os,A:as,B:ns,C:is,D:A,E:ss,F:na,G:ls,H:cs,I:us,J:ds,K:ps,L:ms,M:G,N:le,O:hs,P:fs,Q:ys,R:gs,S:ws,T:bs,U:vs}},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","config","Graphic","rest/locator","symbols/PictureMarkerSymbol","geometry/Extent","geometry/Point","smartMapping/renderers/pieChart","smartMapping/symbology/pieChart","views/support/colorUtils","smartMapping/renderers/color","smartMapping/symbology/color","smartMapping/renderers/univariateColorSize","smartMapping/renderers/dotDensity","smartMapping/symbology/dotDensity","smartMapping/renderers/heatmap","smartMapping/symbology/heatmap","smartMapping/renderers/predominance","smartMapping/symbology/predominance","smartMapping/renderers/relationship","smartMapping/symbology/relationship","smartMapping/renderers/size","smartMapping/renderers/type","smartMapping/symbology/type","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","WebLinkChart","rest/knowledgeGraph/GraphQueryStreaming","views/LinkChartView","rest/knowledgeGraphService","rest/knowledgeGraph/GraphSearchStreaming",a)
|
|
@@ -117,5 +117,4 @@ Do not reinterpret the request into a different form.
|
|
|
117
117
|
- \`requiresFollowUp\` should indicate a likely next agent step, not uncertainty about the current request
|
|
118
118
|
- Set \`requiresFollowUp\` to \`true\` only when another orchestration step will likely be needed after this agent succeeds
|
|
119
119
|
- Set \`requiresFollowUp\` to \`false\` when a successful result from this agent would likely complete the user-visible task
|
|
120
|
-
- Default to \`false\`
|
|
121
120
|
`;export{e as default};
|
|
@@ -97,7 +97,7 @@ ${await sf(J,_,d,$,T,o)}`,id:Fs(),additional_kwargs:{lc_source:"summarization"}}
|
|
|
97
97
|
|
|
98
98
|
`);return o[o.length-1]?.trim()===r?t:`${t}
|
|
99
99
|
|
|
100
|
-
${r}`},Zc=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),If=()=>({agentExecutionContext:he({reducer:qc,default:Zc}),outputMessage:he({reducer:Jc,default:()=>""}),summary:he({reducer:Rn,default:()=>""}),status:he({reducer:Rn})}),_j=()=>({...If(),sharedStatePatch:he({reducer:Rn})}),yj=he.Root({agentExecutionContext:he({default:Zc,reducer:qc}),currentIntent:he({default:()=>"none",reducer:Rn}),lastExecutedAgent:he({default:()=>"",reducer:Rn}),requiresFollowUp:he({default:()=>!0,reducer:Rn}),stepCount:he({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:he({default:()=>"",reducer:Jc})}),go=async(t,e)=>{await Ys("trace_message",t,e)},Aj=async(t,e)=>{await Ys("graph_ux_suggestion",t,e)},xf=(t,e,r)=>{let n=t[e];return n?typeof n=="function"?n():Promise.resolve(n):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},Tf=async t=>(await xf(Object.assign({"./field_descriptions_prompt.md":()=>import("./ZTBA5PM7.js"),"./intent_prompt.md":()=>import("./
|
|
100
|
+
${r}`},Zc=()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}}),If=()=>({agentExecutionContext:he({reducer:qc,default:Zc}),outputMessage:he({reducer:Jc,default:()=>""}),summary:he({reducer:Rn,default:()=>""}),status:he({reducer:Rn})}),_j=()=>({...If(),sharedStatePatch:he({reducer:Rn})}),yj=he.Root({agentExecutionContext:he({default:Zc,reducer:qc}),currentIntent:he({default:()=>"none",reducer:Rn}),lastExecutedAgent:he({default:()=>"",reducer:Rn}),requiresFollowUp:he({default:()=>!0,reducer:Rn}),stepCount:he({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:he({default:()=>"",reducer:Jc})}),go=async(t,e)=>{await Ys("trace_message",t,e)},Aj=async(t,e)=>{await Ys("graph_ux_suggestion",t,e)},xf=(t,e,r)=>{let n=t[e];return n?typeof n=="function"?n():Promise.resolve(n):new Promise((o,s)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(s.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},Tf=async t=>(await xf(Object.assign({"./field_descriptions_prompt.md":()=>import("./ZTBA5PM7.js"),"./intent_prompt.md":()=>import("./FL4W4VYN.js"),"./layer_descriptions_prompt.md":()=>import("./7RCQFLPP.js")}),`./${t}.md`,2)).default,vf=async t=>{let{agent:e,messages:r,config:n}=t;return{structuredResponse:(await e.invoke({messages:r},n)).structuredResponse}},Vc=t=>async(e,r)=>{let n=new Headers(r?.headers);return n.delete("Authorization"),n.delete("api-key"),t&&t.length>0&&(n.set("X-Esri-Authorization",`Bearer ${t}`),n.set("X-Esri-Request-Source","MapsSDK")),await fetch(e,{...r,headers:n})},yo=async(t="default",e=0)=>{let r=aa.getDefault(),n=await Kc.getCredential(`${r.url}/sharing`),o=Wc[t],s=await wf(t);return new ws({modelName:o,apiKey:"dummy-key",...t!=="default"&&{temperature:e},configuration:{baseURL:s,fetch:Vc(n.token)}})},wj=async(t="default")=>{let e=aa.getDefault(),r=await Kc.getCredential(`${e.url}/sharing`),n=la[t],o=await bf(t);return new bs({modelName:n,apiKey:"dummy-key",configuration:{baseURL:o,fetch:Vc(r.token)},batchSize:2048,maxConcurrency:10})},Cf=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(Cf);var Bc=t=>JSON.stringify(t,null,2),Of=t=>{let e=t.map(n=>n.id),r=b.enum(e);return b.object({intent:r.nullable(),assignedTask:b.string().nullable(),requiresFollowUp:b.boolean()})},bj=async(t,e)=>{try{await go({text:"Asking LLM to route to an agent"},e);let r=(e?.configurable?.services.agentRegistry?.list()??[]).map(({agent:d})=>({id:d.id,name:d.name,description:d.description}));if(!r.length)return await go({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none"};let n=await Tf("intent_prompt"),o=Bc(r),s=Of(r),i={registeredAgents:o,priorSteps:Bc(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},a=await Zs.fromTemplate(n).format(i),u=ra({model:await yo("fast"),tools:[],systemPrompt:a,checkpointer:!0,responseFormat:s,middleware:[oa({model:await yo("fast"),trigger:{tokens:4e3},keep:{messages:6}}),sa({runLimit:2})]}),{structuredResponse:l}=await vf({agent:u,messages:t.agentExecutionContext.messages,config:e}),c=s.parse(l??{intent:null,assignedTask:null,requiresFollowUp:!1}),m=c.intent??"none",_={...t,currentIntent:m,requiresFollowUp:c.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:c.assignedTask??""}};if(m==="none"){let d="I could not find a matching agent for that request. Please rephrase your question with more detail.";return await go({text:"LLM did not identify a clear intent."},e),{...t,currentIntent:m,requiresFollowUp:!1,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new S(d)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await go({text:`Agent picked: ${m}
|
|
101
101
|
Task Assigned: ${c.assignedTask??""}
|
|
102
102
|
Requires Follow-Up: ${c.requiresFollowUp}`},e),_}catch(r){throw await go({text:"Error during intent detection"},e),new Error(`Error during intent detection: ${r instanceof Error?r.message:String(r)}`)}},Pf="0.1",_o=1536,kf="openai",Sf=la.default,Mf=`Name: {name}
|
|
103
103
|
Title: {title}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import b from"./
|
|
2
|
+
import b from"./FHVXO2WG.js";import a from"./GSEPHN3A.js";import{Fb as f,a as h,b as l}from"./462JBSEV.js";import{a as y,c as E}from"./HB5A5R2E.js";import"./AMP6IALT.js";import"./OAVEHGB6.js";import{v as u,y as d}from"./OH64RMOR.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{f:p,m:x},{I:c,J:H,a:S,m:_,n:w,o:m,p:v}])=>{var C=[H],b=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:o,fieldRegistry:a},s)=>{let r=Array.from(a.values()).map(n=>n.name).slice(0,10).join(", "),i=a.size>10?` (and ${a.size-10} more)`:"";return`${s+1}. "${o.title}". Description: ${o.description}
|
|
3
3
|
Fields: ${r}${i}`}).join(`
|
|
4
4
|
|
|
5
5
|
`);return`This map contains ${e.size} layer(s):
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import c from"./
|
|
2
|
+
import c from"./YY2SBO3V.js";import b from"./FHVXO2WG.js";import a from"./GSEPHN3A.js";import{Fb as I,a as w,b as h,q as E}from"./462JBSEV.js";import{a as v,c as F}from"./HB5A5R2E.js";import"./AMP6IALT.js";import"./OAVEHGB6.js";import{v as x,y as S}from"./OH64RMOR.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{f:n,m:L},{A:z,B:u,a:$,m:C,o:y,p:N,q:A,r:R,s:T,t:b,u:_,v:V,w:q,x:j,y:k,z:M},D])=>{var B=.7,P=10,J=async(t,r)=>{try{await n({text:"Similarity search to find fields"},r);let e=y(r,"fieldSearch"),i=y(r,"layersAndFieldsRegistry"),o=y(r,"embeddingCache"),a=await e.searchFields({text:t.agentExecutionContext.assignedTask,layerIds:t.vectorSearchLayerIds,minScore:B,topResults:P,embeddingCache:o}),m=a.map(({layerId:c,results:d})=>{let g=d.map(s=>` - ${s.name} (${s.score.toFixed(2)})`).join(`
|
|
3
3
|
`);return`${i.get(c)?.layerItem.name??c}:
|
|
4
4
|
${g}`}).join(`
|
|
5
5
|
`),l;return a.length>0?l=`Vector search completed. Matching layers and fields with scores:
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import{a as S,b as I}from"./7GH7VSB2.js";import{a as M}from"./H7422XUG.js";import"./MH5RPXHM.js";import a from"./
|
|
2
|
+
import{a as S,b as I}from"./7GH7VSB2.js";import{a as M}from"./H7422XUG.js";import"./MH5RPXHM.js";import a from"./GSEPHN3A.js";import{Fb as j,Q as q,W as F,a as P,b as D,eb as O,u as W}from"./462JBSEV.js";import{a as U}from"./AMP6IALT.js";import"./OAVEHGB6.js";import{g as C,h as g,l as R,n as h,t as b,u as v,v as L,w as f,y as A}from"./OH64RMOR.js";import"./YIMNOUTF.js";export default $arcgis.t(([Ie,{whenOnce:_e,watch:ke,when:$e},Ce,Y,ee,J,te,se,,,Re,{property:y,subclass:Le},{b:H,e:N,f:m,h:z,i:V,j:T}])=>{var re=async t=>{let e=await ie(),s=await H("default"),i=ee.getDefault(),r=(await Y.getCredential(`${i.url}/sharing`)).token,a={type:"generateEmbeddings",webmapEmbeddings:t,auth:{apiUrl:s,token:r}};return e.postMessage(a),await new Promise((n,c)=>{let o=l=>{l.data==="completed"&&(e.removeEventListener("message",o),n())},d=l=>{e.removeEventListener("message",o),c(l instanceof Error?l:new Error("Embeddings worker error"))};e.addEventListener("message",o),e.addEventListener("error",d,{once:!0})}),e},ie=async()=>{{let t=(await import("./23EQTPO3.js")).default;return new t}},ae=t=>{t.currentIntent="none"},ne=async(t,e)=>{if(t.agentExecutionContext.userRequest){let i=new F(t.agentExecutionContext.userRequest.trim());t.agentExecutionContext.messages=[...t.agentExecutionContext.messages,i],ae(t)}let s=e?.configurable?.services.agentRegistry.list().map(i=>i.agent.id)??[];return await m({text:`Available agents: ${[...s].join(", ")}`},e),await m({text:"Analyzing user input"},e),t},oe=async(t,e)=>(await m({text:"Exiting..."},e),t),B=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),ce=(t,e)=>{if(!B(t)){t!==void 0&&console.warn(`Agent "${e}" returned invalid sharedStatePatch. Ignoring it.`);return}let s={};for(let[i,r]of Object.entries(t)){if(!B(r)||!("value"in r)){console.warn(`Agent "${e}" returned invalid sharedStatePatch entry for key "${i}". Ignoring that entry.`);continue}s[i]={value:r.value}}return s},de=t=>{let{previousSharedState:e,patch:s,agentId:i}=t;if(!s)return e;let r=Date.now(),a={...e};for(let[n,c]of Object.entries(s))c?.value!==void 0&&(a[n]={value:c.value,meta:{updatedByAgentId:i,updatedAt:r}});return a},G=t=>typeof t!="string"?void 0:t.trim()||void 0,le=t=>{switch(t){case"failed":return"Agent failed without a summary.";case"unknown":return"Agent returned with unknown status.";case"success":return"Agent completed without a summary.";default:return"Agent completed without a summary."}},ge=(t,e)=>{let s=G(e?.outputMessage),i=G(e?.summary),r=e?.status,a=r==="success"||r==="failed"?r:"unknown";a==="unknown"&&console.warn(`Agent "${t}" returned missing/invalid status. Defaulting to "unknown".`);let n=ce(e?.sharedStatePatch,t);return{outputMessage:s,summary:i??s??le(a),status:a,sharedStatePatch:n}},Q=4e3,he=async(t,e)=>{let s=e?.configurable,{agentRegistry:i}=s.services,r=i?.get(t.currentIntent);if(!r)return console.warn(`No agent found for intent: ${t.currentIntent}`),t;await m({text:`Executing registered agent: ${r.agent.name}`},e);let a={...e??{},configurable:{...s??{},agentId:r.agent.id,context:r.getContext?await r.getContext():void 0}},n;try{let d=await r.agent.createGraph().compile().invoke({agentExecutionContext:{...t.agentExecutionContext,messages:[...t.agentExecutionContext.messages],priorSteps:structuredClone(t.agentExecutionContext.priorSteps??[]),sharedState:structuredClone(t.agentExecutionContext.sharedState??{})}},a);n=ge(r.agent.name,d),await m({text:`Finished executing registered agent: ${r.agent.name}`},e)}catch(d){if(W(d))throw d;let l=d instanceof Error?d.message:String(d);console.error(`Agent "${r.agent.name}" failed:`,d),await m({text:`Registered agent failed: ${r.agent.name}. ${l}`},e),n={status:"failed",outputMessage:`Agent execution failed: ${l}`,summary:`Agent execution failed: ${l}`}}let c=n.outputMessage,o=[...t.agentExecutionContext.messages];if(c){let d=c.length>Q?`${c.slice(0,Q-14)}
|
|
3
3
|
[truncated]`:c;o.push(new q(d))}return{...t,stepCount:t.stepCount+1,lastExecutedAgent:r.agent.id,requiresFollowUp:n.status==="failed"?!0:t.requiresFollowUp,finalOutputMessage:c??"",agentExecutionContext:{...t.agentExecutionContext,messages:o,priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:r.agent.id,assignedTask:t.agentExecutionContext.assignedTask,summary:n?.summary||"No summary provided.",status:n?.status||"unknown"}],sharedState:de({previousSharedState:t.agentExecutionContext.sharedState,patch:n.sharedStatePatch,agentId:r.agent.id})}}},ue=3,pe=()=>new j(N).addNode("ingestInput",ne).addNode("intentLLM",V).addNode("executeRegisteredAgent",he).addNode("exit",oe).addEdge(P,"ingestInput").addEdge("ingestInput","intentLLM").addConditionalEdges("intentLLM",t=>t.currentIntent==="none"||t.currentIntent===t.lastExecutedAgent?"exit":"executeRegisteredAgent").addConditionalEdges("executeRegisteredAgent",t=>t.stepCount>=ue||!t.requiresFollowUp?"exit":"intentLLM").addEdge("exit",D),_=class{constructor(){this.agentRegistry=new Map}register(e){let{agent:s}=e;if(this.agentRegistry.has(s.id))throw new Error(`Duplicate agent id: ${s.id}`);this.agentRegistry.set(s.id,e)}get(e){return this.agentRegistry.get(e)}list(){return[...this.agentRegistry.values()]}},k=class{constructor(e,s){this.graph=e,this.config={...s}}async waitForUser(){return await new Promise((e,s)=>{this.resolveWait=e,this.rejectWait=s})}handle(e,s){try{let i={agentId:e.agentId,id:e.id,payload:s},r=this.graph.streamEvents(null,{...this.config,configurable:{...this.config.configurable,hitlResponse:i},subgraphs:!0,version:"v2"});this.resolveWait?.(r)}catch(i){this.rejectWait?.(i)}finally{this.resolveWait=void 0,this.rejectWait=void 0}}cancel(){this.rejectWait&&(this.rejectWait(new Error("Request cancelled by user.")),this.resolveWait=void 0,this.rejectWait=void 0)}},me=async t=>{try{return await(await z()).embedDocuments(t)}catch(e){throw console.error("Failed to generate embeddings:",e),e}},K=async(t,e)=>{let s=e.get(t);if(s)return s;let i=await me([t]);return e.set(t,i[0]),i[0]};async function ye(t,e,s,i){let r=`req-${Date.now()}`,a={type:"layerSearch",precomputedEmbedding:i?await K(t,i):void 0,requestId:r,minScore:s};return await new Promise(n=>{let c=o=>{o.data.requestId===r&&n(o.data.results)};e.addEventListener("message",c,{once:!0}),e.postMessage(a)})}function we(t){let{worker:e}=t;return{async searchLayers({text:s,minScore:i,embeddingCache:r}){return await ye(s,e,i,r)}}}var fe=async({combinedQuery:t,layerIds:e,embeddingsWorker:s,minScore:i,topResults:r,embeddingCache:a})=>{let n=`req-${Date.now()}`,c=a?await K(t,a):void 0,o={type:"fieldSearch",layerIdForFieldsSearch:e,precomputedEmbedding:c,requestId:n,minScore:i,topResults:r};return await new Promise(d=>{let l=w=>{if(w.data.requestId!==n)return;let x=w.data.results.map(({layerId:Z,results:X})=>({layerId:Z,results:X}));d(x)};s.addEventListener("message",l,{once:!0}),s.postMessage(o)})};function be(t){let{worker:e}=t;return{async searchFields({text:s,layerIds:i,minScore:r,topResults:a,embeddingCache:n}){return await fe({combinedQuery:s,layerIds:i,embeddingsWorker:e,minScore:r,topResults:a,embeddingCache:n})}}}var ve=t=>{let e=T.safeParse(t);if(!e.success)throw new Error("Embeddings response validation failed. Regenerate embeddings.");return e.data},Ee=(t,e)=>{let s=new Map,i=new Map;if(e.allLayers.forEach(r=>{r instanceof te&&i.set(r.id,r)}),t.length!==i.size)throw new Error("Layer count mismatch during registry restoration. Regenerate embeddings.");for(let r of t){let a=i.get(r.id);if(!a)throw new Error(`Layer with ID ${r.id} not found in the original map during registry restoration. Regenerate embeddings.`);if(r.fields.length!==a.fields.length)throw new Error(`Field count mismatch for layer ID ${r.id} during registry restoration. Regenerate embeddings.`);let n={name:r.name,title:r.title,description:r.description},c=new Map;for(let o of r.fields){let d=a.fieldsIndex.get(o.name);if(!d)throw new Error(`Field with name ${o.name} not found in the original layer ${r.id} during registry restoration. Regenerate embeddings.`);c.set(o.name,{name:o.name,alias:a.getFieldAlias(o.name)??o.alias,description:o.description,type:d.type||"unknown",valueType:d.valueType||"unknown",domain:a.getFieldDomain(o.name)??void 0})}s.set(r.id,{layerItem:n,fieldRegistry:c})}return s},xe=async t=>{try{return(await se(t,{responseType:"json"})).data}catch(e){throw new Error(`Failed to fetch data from ${t}: ${String(e)}`)}},Se=async t=>{let e=t.map;if(!e?.portalItem)throw new Error("WebMap portal item is missing.");let{resources:s}=await e.portalItem.fetchResources(),i=s.find(a=>a.resource.path==="embeddings-v01.json");if(!i?.resource.url)throw new Error("Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.");let r=await xe(i.resource.url);return ve(r)},E=class t{constructor(){this.orchestratorReady=!1,this.chatHistory=[],this.priorSteps=[],this.sharedState={},this.threadId="",this.agentRegistry=new _,this.streamEpoch=0}static async init(e){let s=new t;try{if(e.view?.map){await J.whenOnce(()=>e.view.ready);let i=await Se(e.view),r=Ee(i.layers,e.view.map);s.layersAndFieldsRegistry=r,s.embeddingsWorker=await re(i)}return e.agents?.forEach(i=>{s.agentRegistry.register(i)}),s.orchestratorReady=!0,s}catch(i){throw console.error("Orchestrator initialization failed:",i),i}}async*ask(e){if(!this.orchestratorReady)throw new Error("Orchestrator is not ready yet.");if(!this.agentRegistry.list().length)throw new Error("Orchestrator has no registered agents.");if(++this.streamEpoch,!e.trim())return;this.threadId=String(Date.now()),this.graph||(this.graph=pe().compile({checkpointer:new O}));let s=this.embeddingsWorker?we({worker:this.embeddingsWorker}):void 0,i=this.embeddingsWorker?be({worker:this.embeddingsWorker}):void 0,r=new Map,a={version:"v2",streamMode:"custom",configurable:{thread_id:this.threadId,hitlResponse:null,services:{layerSearch:s,fieldSearch:i,layersAndFieldsRegistry:this.layersAndFieldsRegistry,agentRegistry:this.agentRegistry,embeddingCache:r}},subgraphs:!0},n=this.graph?.streamEvents({agentExecutionContext:{userRequest:e,messages:this.chatHistory,priorSteps:this.priorSteps,sharedState:this.sharedState}},a),c=++this.streamEpoch;for(yield*this.pipeStream(n,c);;){let d=(await this.graph.getState(a,{subgraphs:!0})).tasks.find(l=>l.interrupts.length>0)?.interrupts[0]?.value;if(!d)break;this.currentInterrupt=d,this.interruptHandler=new k(this.graph,a),yield{runId:this.threadId,timestamp:Date.now(),type:"interrupt",interrupt:d};try{let l=await this.interruptHandler.waitForUser(),w=++this.streamEpoch;yield*this.pipeStream(l,w)}catch(l){if(l){yield{runId:this.threadId,timestamp:Date.now(),type:"error",error:{message:l?.message}};return}yield{runId:this.threadId,timestamp:Date.now(),type:"cancelled"};return}}let o=(await this.graph.getState(a,{subgraphs:!0})).values;this.chatHistory=o.agentExecutionContext.messages.length?o.agentExecutionContext.messages:this.chatHistory,this.priorSteps=o.agentExecutionContext.priorSteps?.slice(-5)??[],this.sharedState=o.agentExecutionContext.sharedState??{},yield{runId:this.threadId,timestamp:Date.now(),type:"completed",result:{content:o.finalOutputMessage}}}newConversation(){this.chatHistory=[],this.priorSteps=[],this.sharedState={}}resumeInterrupt(e){if(!this.currentInterrupt||!this.interruptHandler)throw new Error("No pending interrupt to resume.");this.interruptHandler.handle(this.currentInterrupt,e)}cancelInterrupt(){this.interruptHandler&&this.interruptHandler.cancel()}async*pipeStream(e,s){for await(let i of e){if(s!==this.streamEpoch){console.log("Stale stream detected, aborting.");break}i.event==="on_custom_event"&&i.name==="trace_message"?yield{runId:this.threadId,timestamp:Date.now(),type:"trace",data:i.data}:i.name==="graph_ux_suggestion"&&(yield{runId:this.threadId,timestamp:Date.now(),type:"ux-suggestion",suggestion:i.data})}}dispose(){this.embeddingsWorker&&(this.embeddingsWorker.terminate(),this.embeddingsWorker=void 0),this.orchestratorReady=!1}};var Ae=C`:host{display:block;width:var(--arcgis-internal-panel-width, 100%);height:var(--arcgis-internal-expand-max-height, 100%)}.footer-container{display:flex;flex-direction:column;flex:1 1 0;gap:var(--calcite-spacing-md)}.content-container{display:flex;flex-direction:column;flex:1 1 0;min-height:0;position:relative;overflow:auto}.suggested-prompts-container{display:flex;justify-content:center;width:100%}.suggested-prompts{display:block;padding:var(--calcite-spacing-md);max-width:100%;box-sizing:border-box}.error-notice{padding:var(--calcite-spacing-sm)}`,Me=Object.defineProperty,Pe=Object.getOwnPropertyDescriptor,p=(t,e,s,i)=>{for(var r=i>1?void 0:i?Pe(e,s):e,a=t.length-1,n;a>=0;a--)(n=t[a])&&(r=(i?n(e,s,r):n(r))||r);return i&&r&&Me(e,s,r),r},u=class extends Re{constructor(t){super(t),this.view=null,this.loading=!1,this.processing=!1,this.processingStep=""}async load(){this._set("loading",!0);try{await this._initialize()}finally{this._set("loading",!1)}}destroy(){this.orchestrator?.dispose(),super.destroy()}async _initialize(){this.removeHandles(),await Promise.all([this.portal.load(),this.view?.when()]),this.view&&await _e(()=>!this.view.updating),this._set("orchestrator",await E.init({agents:[...this.agents],view:this.view??void 0})),this.addHandles([ke(()=>[this.view,this.agents],()=>{this._initialize()})])}clearChatHistory(){this.orchestrator?.newConversation()}async*ask(t,e){if(!this.orchestrator)throw new Error("Orchestrator not initialized yet.");this._set("processing",!0),this._set("processingStep","");let s=[],i;try{let r=this.orchestrator.ask(t);for await(let a of r){let n=a.runId;if(e?.aborted){yield{type:"cancelled",runId:n};break}switch(a.type){case"trace":{this._set("processingStep",a.data.text),s.push(a.data.text);break}case"completed":{let c=a.result,o=!!c.content.length,d=!!i?.length;if(!o&&!d){yield{type:"completed",error:"Could not process the request.",log:s,runId:n};return}let l=c.content;this._set("processingStep",""),yield{type:"completed",response:l,blocks:i,log:s,runId:n};return}case"ux-suggestion":{let c=a.suggestion;i=i?[...i,c]:[c];break}case"interrupt":{let{kind:c,message:o,metadata:d}=a.interrupt,l=Array.isArray(d)?d.filter(x=>typeof x=="string"):[],w=(()=>{switch(c){case"booleanChoice":return{type:"boolean-choice",message:o,options:l};case"singleSelection":return{type:"single-select",message:o,options:l};case"multipleSelection":return{type:"multi-select",message:o,options:l};case"textInput":return{type:"text-input",message:o};default:return{type:c,message:o,options:l}}})();this._set("processingStep","Waiting for user input..."),yield{type:"interrupt",payload:w,runId:n};break}case"cancelled":{yield{type:"cancelled",runId:n};return}case"error":{yield{type:"completed",error:a.error.message,log:s,runId:n};return}default:{console.warn("Unknown event type:",a);break}}}}catch(r){console.warn("Error during message processing:",r),yield{type:"completed",error:"An error occurred during message processing.",log:s,runId:"error"};return}finally{this._set("processing",!1)}}};p([y({readOnly:!0})],u.prototype,"orchestrator",2);p([y()],u.prototype,"agents",2);p([y()],u.prototype,"portal",2);p([y()],u.prototype,"view",2);p([y({readOnly:!0})],u.prototype,"loading",2);p([y({readOnly:!0})],u.prototype,"processing",2);p([y({readOnly:!0})],u.prototype,"processingStep",2);u=p([Le("OrchestratorController")],u);var De="Embeddings resource 'embeddings-v01.json' not found in the webmap portal item.",We="Embeddings not found for this web map.",qe="https://developers.arcgis.com/javascript/latest/agentic-apps/ai-webmap-setup/#embeddings",$=class extends L{constructor(){super(...arguments),this._messages=M({blocking:!0}),this.#e=b(),this.#n=b(),this.#t=b(),this.#s=null,this.#o=new Map,this.#r=Ce.getDefault(),this.#i=e=>{e.stopPropagation(),this.cancelInterrupt()},this.#a=e=>{e.stopPropagation();let s=e.detail;this.submitInterrupt(s)},this.#c=e=>{e.stopPropagation(),this.keepSuggestedPrompts||(this.suggestedPrompts=[]);let s=e.detail;this._inputValue="",this.arcgisSubmit.emit(s),this.submitMessage(s)},this.#d=e=>{if(e.stopPropagation(),this.arcgisCancel.emit(),this._interrupt){this.orchestrator?.cancelInterrupt(),this._interrupt=null;return}this.#s?.abort()},this.#l=e=>{e.stopPropagation();let s=e.detail;this.arcgisFeedback.emit(s)},this.#g=e=>{e.stopPropagation();let s=e.detail;this._inputValue=s.prompt,this.arcgisPromptSelect.emit(s)},this.#h=e=>{this.arcgisSlottableRequest.emit(e.detail)},this._orchestratorController=null,this._interrupt=null,this._error=null,this._inputValue="",this.messages=new Ie([]),this.referenceElement=null,this.suggestedPrompts=[],this.feedbackEnabled=!1,this.keepSuggestedPrompts=!1,this.logEnabled=!1,this.copyEnabled=!1,this.voiceInputEnabled=!1,this.readAloudEnabled=!1,this.arcgisCancel=h(),this.arcgisError=h(),this.arcgisFeedback=h(),this.arcgisInterrupt=h(),this.arcgisInterruptCancel=h(),this.arcgisInterruptSubmit=h(),this.arcgisPromptSelect=h(),this.arcgisReady=h(),this.arcgisSubmit=h(),this.arcgisSlottableRequest=h({bubbles:!1,composed:!1})}static{this.properties={_orchestratorController:16,_interrupt:16,_error:16,_inputValue:16,_user:16,awaitingResponse:32,awaitingResponseStep:32,interrupt:32,messages:0,orchestrator:32,entryMessage:1,heading:1,description:1,referenceElement:1,suggestedPrompts:0,feedbackEnabled:5,keepSuggestedPrompts:5,logEnabled:5,copyEnabled:5,voiceInputEnabled:5,readAloudEnabled:5}}static{this.styles=Ae}#e;#n;#t;#s;#o;#r;#i;#a;#c;#d;#l;#g;#h;async#u(){try{let e=U(this.el,this.referenceElement);await e?.componentOnReady();let s=[...this.#o.values()];return s.length?(this._orchestratorController=new u({agents:s,portal:this.#r,view:e?.view}),await this._orchestratorController.load(),!0):(this._error="No agents found.",!1)}catch(e){return this._error=e?.message??"Error initializing orchestrator.",R(this)(e),!1}}get _user(){return this.#r?.user?.fullName||this.#r?.user?.username}get awaitingResponse(){return this._orchestratorController?.processing??!1}get awaitingResponseStep(){return this._orchestratorController?.processingStep??""}get interrupt(){return this._interrupt}get orchestrator(){return this._orchestratorController?.orchestrator}async clearChatHistory(){this._reset(),this._orchestratorController?.clearChatHistory()}cancelInterrupt(){this.arcgisInterruptCancel.emit(),this.orchestrator?.cancelInterrupt(),this._interrupt=null}register(e){this.#o.set(e.agent.id,e)}async submitMessage(e){let s=e.trim();if(!s||(this.messages.push({id:Date.now().toString(),role:"user",content:s}),!this._orchestratorController))return;let i=this._orchestratorController.ask(s,this.#s?.signal);for await(let r of i){let a=r.runId;switch(r.type){case"completed":this.messages.push({role:"assistant",content:r.response,blocks:r.blocks,log:r.log,error:r.error,id:a});break;case"interrupt":this._interrupt={...r.payload,id:a},this.arcgisInterrupt.emit(this._interrupt);break;case"cancelled":this.messages.push({role:"assistant",error:"Request cancelled.",id:a});break}}}submitInterrupt(e){this.arcgisInterruptSubmit.emit(e),this.orchestrator?.resumeInterrupt(e),this._interrupt=null}load(){this.manager.onLifecycle(this._reset.bind(this))}loaded(){this.manager.onLifecycle(()=>{this.#e.value?.addEventListener("arcgisPromptSelect",this.#g),this.#e.value?.addEventListener("arcgisSubmit",this.#c),this.#e.value?.addEventListener("arcgisCancel",this.#d),this.#e.value?.addEventListener("arcgisFeedback",this.#l);let e=$e(()=>!!this._interrupt&&!!this.#t.value,()=>{let s=this.#t.value;s.removeEventListener("arcgisSubmit",this.#a),s.removeEventListener("arcgisCancel",this.#i),s.addEventListener("arcgisSubmit",this.#a,{once:!0}),s.addEventListener("arcgisCancel",this.#i,{once:!0})});return queueMicrotask(()=>{this.#u().then(s=>{s?this.arcgisReady.emit():this._error&&this.arcgisError.emit(new Error(this._error))})}),()=>{e.remove(),this.#e.value?.removeEventListener("arcgisPromptSelect",this.#g),this.#t.value?.removeEventListener("arcgisSubmit",this.#a),this.#t.value?.removeEventListener("arcgisCancel",this.#i),this.#e.value?.removeEventListener("arcgisSubmit",this.#c),this.#e.value?.removeEventListener("arcgisCancel",this.#d),this.#e.value?.removeEventListener("arcgisFeedback",this.#l),this._orchestratorController?.destroy(),this._orchestratorController=null}})}_reset(){this.#s?.abort(),this._interrupt=null,this.messages.removeAll(),this._error=null,this._inputValue=""}_renderEntryMessage(){return this._interrupt?g`<slot name=interrupt><arcgis-assistant-interrupt .type=${this._interrupt.type} .message=${this._interrupt.message} .options=${this._interrupt.options} ${v(this.#t)}></arcgis-assistant-interrupt></slot>`:this._error?this._renderErrorNotice():this.entryMessage?this.messages.length>0?null:g`<calcite-notice open kind=info closable icon width=full><div slot=message>${this.entryMessage}</div></calcite-notice>`:g`<slot name=entry-message></slot>`}_renderErrorNotice(){return this._error?g`<calcite-notice closable slot=entry-message open kind=danger icon width=full>${this._error===De?g`<div slot=message>${We}</div><calcite-link slot=link .href=${qe} target=_blank title="Learn about web map embeddings">Read more</calcite-link>`:g`<div slot=message>${this._error}</div>`}</calcite-notice>`:null}_renderSuggestedPrompts(){return this.suggestedPrompts?.length?g`<div class="suggested-prompts-container"><arcgis-assistant-suggested-prompts class="suggested-prompts" .prompts=${this.suggestedPrompts}></arcgis-assistant-suggested-prompts></div>`:null}render(){return g`<calcite-panel .loading=${!this._orchestratorController&&!this._error||this._orchestratorController?.loading} .heading=${this.heading??this._messages.assistantLabel} .description=${this.description} ${v(this.#e)}><slot name=header-actions-start slot=header-actions-start></slot><slot name=header-actions-end slot=header-actions-end></slot><div class="content-container"><arcgis-assistant-chat .loading=${this.awaitingResponse} .messages=${this.messages}><slot name=message-starter slot=message-starter></slot><slot name=messages slot=messages>${this.messages.map(e=>e.role==="assistant"?g`<arcgis-assistant-message .message=${e} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled} @arcgisSlottableRequest=${this.#h}><slot name=${S(e.id)??f} slot=${S(e.id)??f}>${e?.error?g`<calcite-notice class="error-notice" open icon kind=warning width=full><div slot=message>${e.error}</div></calcite-notice>`:g`<arcgis-assistant-message-text .content=${e?.content}></arcgis-assistant-message-text>`}</slot>${e.blocks?.map((s,i)=>g`<slot name=${I(e.id,i)??f} slot=${I(e.id,i)??f}><arcgis-assistant-message-block .block=${s}></arcgis-assistant-message-block></slot>`)}</arcgis-assistant-message>`:g`<arcgis-assistant-user-message .message=${e} .user=${this._user}></arcgis-assistant-user-message>`)}</slot><slot name=message-loading slot=message-loading><arcgis-assistant-message-loading .loading=${this.awaitingResponse} .loadingMessage=${this.awaitingResponseStep}></arcgis-assistant-message-loading></slot></arcgis-assistant-chat></div>${this._renderSuggestedPrompts()}<div class="footer-container" slot=footer>${this._renderEntryMessage()}<slot name=chat-entry><arcgis-assistant-chat-entry .awaitingResponse=${this.awaitingResponse} .inputValue=${this._inputValue} .messages=${this.messages} .voiceInputEnabled=${this.voiceInputEnabled} ${v(this.#n)}><slot name=entry-actions-start slot=entry-actions-start></slot><slot name=entry-actions-end slot=entry-actions-end><calcite-button .iconStart=${this.awaitingResponse?"circle-stop":"send"} @click=${()=>{this.#n.value?.submitMessage()}} round>${this.awaitingResponse?this._messages.stopButtonLabel:this._messages.askButtonLabel}</calcite-button></slot></arcgis-assistant-chat-entry></slot><slot name=footer-content></slot></div></calcite-panel>`}};A("arcgis-assistant",$);return $},"core/Collection","core/reactiveUtils","portal/Portal","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","layers/FeatureLayer","core/Accessor","core/accessorSupport/decorators",a)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import b from"./
|
|
2
|
+
import b from"./FHVXO2WG.js";import a from"./GSEPHN3A.js";import{Fb as C,a as N,b as T}from"./462JBSEV.js";import{a as L,c as R}from"./HB5A5R2E.js";import"./AMP6IALT.js";import"./OAVEHGB6.js";import{v as E,y as $}from"./OH64RMOR.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,,,,,{a:f,f:d,l:b,m:F},{a:_,b:v,c:x,d:I,e:A,f:M,g:Z,h:q,i:j,j:V,k:O,l:z,m:S,n:G,o:h,p:B}])=>{var w=[I,A,M,Z,q,j,V,O,z];async function H(e,t){let a=await S("navigation_tool_prompt"),{mapView:r}=x(t),l=r.map.bookmarks?.map(p=>p.name).filter(Boolean)??[],i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((p,W)=>`${W+1}. layerId=${p.id} | title=${p.title??""} | name=${p.name??""} | score=${p.score.toFixed(2)}`).join(`
|
|
3
3
|
`):"",c=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",n=e.intent==="goToBookmark"&&l.length?`Available bookmarks:
|
|
4
4
|
${l.map(p=>`- ${p}`).join(`
|
|
5
5
|
`)}`:"",o=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import d from"./YY2SBO3V.js";import c from"./FHVXO2WG.js";import a from"./GSEPHN3A.js";import{Fb as k,Q as V,a as N,b as E}from"./462JBSEV.js";import{a as D,c as O}from"./HB5A5R2E.js";import"./AMP6IALT.js";import"./OAVEHGB6.js";import{v as b,y as A}from"./OH64RMOR.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,K,X,,,{f:n,k:z,m:T},{C:R,D:G,E:L,F:P,G:F,H:U,a:j,m:S,n:M,o:p,p:Q},C])=>{var Y=async(e,t)=>(await n({text:"Exiting Data Exploration agent"},t),e),Z=async(e,t)=>{await n({text:"Requesting LLM for layer filter results"},t);let a=await S("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:c,userTimezoneOffset:l}=L(),s={layerFieldInfo:e.layerFieldInfo,userTimezone:c,userTimezoneOffset:l,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},r=await T({promptText:a,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:s,tools:F}),i=[...e.dataExplorationMessages,r];if(!((r.tool_calls?.length??0)>0))return await n({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:i};let u=[...i,r],o=r.content.toString();return await C(r,t),{...e,dataExplorationMessages:u,outputMessage:o}},ee=async(e,t)=>{await n({text:"Requesting LLM for layer query results"},t);let a=await S("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:c,userTimezoneOffset:l}=L(),s=e.agentExecutionContext.sharedState.lastNavigatedFeatures,r=s&&typeof s=="object"&&"value"in s?s.value:s,i="none";if(r!=null)try{i=JSON.stringify(r)}catch{i="none"}let u={layerFieldInfo:e.layerFieldInfo,userTimezone:c,userTimezoneOffset:l,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps,lastNavigatedFeatures:i},o=await T({promptText:a,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:u,tools:P}),m=o.content.toString();return await C(o,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,o],outputMessage:m,status:"success",summary:m?M(m):"Query executed."}},te=async(e,t)=>{try{await n({text:"Requesting LLM for summary on query results"},t);let a=await S("summarize_query_response_prompt"),c={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},l=await z({promptText:a,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:c}),s=typeof l=="string"?l:l.content,r=new V(s);await n({text:`Received response from LLM: ${s}`},t);let i=s;return{...e,outputMessage:i,status:"success",summary:i?M(i):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,r]}}catch(a){throw await n({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${a instanceof Error?a.message:String(a)}`)}};async function ae(e,t){let a=await new j(F).invoke({messages:e.dataExplorationMessages},t);return await n({text:`Finished executing layer filter tool: ${a.messages.map(c=>c.content).join(", ")}`},t),{...e}}var se=10,re=["string","small-integer","integer"],ie=async(e,t,{includeSummaryStatistics:a=!0,includeUniqueValues:c=!0}={})=>{let l=null,s=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){a&&(l=await K({layer:e,field:t.name}));let r=t.domain?.type==="coded-value"?t.domain:null;c&&(re.includes(t.type)||r)&&(s=(await X({layer:e,field:t.name})).uniqueValueInfos.sort((i,u)=>u.count-i.count).slice(0,se),r&&(s=s.map(i=>({...i,value:r.getName(i.value)??i.value}))))}}catch(r){console.error(`Error fetching statistics for field ${t.name}:`,r)}return{summaryStatistics:l,uniqueValues:s}};function oe(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function ne(e,t,a,c=!0){let l=[],s=[],r=[];for(let i of e){let u=function(g){let d=t.get(g)?.layerItem;return d?[d.name&&`Name: ${d.name}`,d.title&&`Title: ${d.title}`,d.description&&`Description: ${d.description}`].filter(Boolean).join(" | "):g},{layerId:o,results:m}=i,f=a.map?.allLayers.find(g=>g.id===o),w=t.get(o)?.fieldRegistry;if(!w)continue;let h=l.find(g=>g.layerId===o);h||(h={layerId:o,layerSummary:u(o),fieldInfos:[]},l.push(h));for(let g of m){let d=w.get(g.name);if(!d)continue;let y=d.statistics,v=c&&!y?.summaryStatistics,q=oe(d.type,d.domain?.type)&&!y?.uniqueValues,_=v||q;if(r.push({layerId:o,fieldName:d.name,didFetchStatistics:_}),_){let J=ie(f,d,{includeSummaryStatistics:v,includeUniqueValues:q}).then($=>{let x={summaryStatistics:y?.summaryStatistics??null,uniqueValues:y?.uniqueValues??null};v&&(x.summaryStatistics=$.summaryStatistics),q&&(x.uniqueValues=$.uniqueValues),w.set(d.name,{...d,statistics:x}),d.statistics=x});s.push(J)}h.fieldInfos.push(d)}}return await Promise.all(s),{layerFieldInfo:l,didFetchStatistics:s.length>0,fieldStatisticsFetchStatus:r}}var W=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function le(e,t){return W.test(e)||W.test(t)}var de=async(e,t)=>{try{await n({text:"Preparing field information for vector search results"},t);let a=p(t,"layersAndFieldsRegistry"),{mapView:c}=G(t),{assignedTask:l,userRequest:s}=e.agentExecutionContext,r=le(l,s),{layerFieldInfo:i,didFetchStatistics:u,fieldStatisticsFetchStatus:o}=await ne(e.vectorSearchFieldResults,a,c,r);u?await n({text:"Statistics fetched"},t):await n({text:"Statistics skipped"},t);for(let m of o)await n({text:` - ${m.fieldName} - stats ${m.didFetchStatistics?"fetched":"skipped"}`},t);return await n({text:"Field information prepared"},t),{...e,layerFieldInfo:i}}catch(a){throw await n({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${a instanceof Error?a.message:String(a)}`)}},B=.7,ce=10,ue=async(e,t)=>{try{await n({text:"Similarity search to find fields"},t);let a=p(t,"fieldSearch"),c=p(t,"layersAndFieldsRegistry"),l=p(t,"embeddingCache"),s=await a.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:B,topResults:ce,embeddingCache:l}),r=s.map(({layerId:u,results:o})=>{let m=o.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
|
|
3
|
+
`);return`${c.get(u)?.layerItem.name??u}:
|
|
4
|
+
${m}`}).join(`
|
|
5
|
+
`),i;return s.length>0?i=`Vector search completed. Matching layers and fields with scores:
|
|
6
|
+
${r}`:i=`No vector search results found for score over ${B}.`,await n({text:i},t),{...e,vectorSearchFieldResults:s}}catch(a){throw await n({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},me=.7,ge=async(e,t)=>{try{await n({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let a=p(t,"layerSearch"),c=p(t,"layersAndFieldsRegistry"),l=p(t,"embeddingCache"),s=await a.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:me,embeddingCache:l}),r=s.map(o=>o.id),i=s.map(({id:o,score:m})=>`${c.get(o)?.layerItem.name??o} (${m.toFixed(2)})`).join(`
|
|
7
|
+
`),u;return r.length>0?u=`Vector search completed. Matching layers with scores:
|
|
8
|
+
${i}`:u="Vector search completed. No matching layers found.",await n({text:u},t),{...e,vectorSearchLayerIds:r}}catch(a){throw await n({text:`Error during vector search: ${a instanceof Error?a.message:String(a)}`},t),new Error(`Vector search failed: ${a instanceof Error?a.message:String(a)}`)}},pe=(e,t)=>Q(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),fe=()=>new k(R).addNode("requireDataExplorationServices",pe).addNode("vectorSearchLayers",ge).addNode("vectorSearchFields",ue).addNode("fieldStatistics",de).addNode("queryAgent",ee).addNode("queryTools",U).addNode("summarizeQueryResponseLLM",te).addNode("filterAgent",Z).addNode("filterTools",ae).addNode("earlyExit",Y).addEdge(N,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":E).addEdge("filterTools",E).addEdge("earlyExit",E),he=String.raw`- **data exploration** — User is asking about the feature layer’s data (e.g. counts, summaries, statistics, field values), either for all features, a subset based on a condition, or for a subset based on the current view. And/Or user wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
|
|
9
|
+
The Data Exploration Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
|
|
10
|
+
_Example: “Only show stations where Brand is Shell”_
|
|
11
|
+
_Example: “Make Shell stations stand out on the map”_
|
|
12
|
+
_Example: “Gray out all stations that aren’t Shell”_
|
|
13
|
+
This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
|
|
14
|
+
_Example: “How many features are there?”_
|
|
15
|
+
_Example: “What’s the average population?”_
|
|
16
|
+
_Example: “Which values are in the status field?”_`,H={id:"dataExploration",name:"Data Exploration Agent",description:he,createGraph:fe,workspace:R};var I=class extends b{constructor(){super(...arguments),this.agent=H}static{this.properties={referenceElement:1}}#e;getContext(){if(!this.#e)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#e}}load(){this.#e=D(this,"arcgis-assistant-data-exploration-agent"),O(this)}};A("arcgis-assistant-data-exploration-agent",I);return I},"identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","identity/IdentityManager","portal/Portal","core/reactiveUtils","layers/FeatureLayer","request","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","views/LinkChartView","rest/knowledgeGraphService",a,c,d)
|