@arcgis/ai-components 5.0.0-next.149 → 5.0.0-next.150
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/README.md +2 -3
- package/dist/cdn/{NRKOPZOT.js → 33UOPY5K.js} +1 -1
- package/dist/cdn/{NAZFDJLE.js → 4H44OILN.js} +1 -1
- package/dist/cdn/{ASR4DPYD.js → 7JQF7K4O.js} +1 -1
- package/dist/cdn/{FQFDDYVF.js → 7XU5DHDB.js} +1 -1
- package/dist/cdn/{OEF6YVL2.js → AHBZA3FR.js} +1 -1
- package/dist/cdn/{LSDCO6AG.js → CFWC26EG.js} +1 -1
- package/dist/cdn/{CEXAIP2B.js → EF43HQG4.js} +1 -1
- package/dist/cdn/{U3AQJYZ7.js → JMVSBIZH.js} +1 -1
- package/dist/cdn/{LI7VOWXM.js → M3HTSZRF.js} +99 -95
- package/dist/cdn/{JCZAM66N.js → M7LOJK3R.js} +1 -1
- package/dist/cdn/{UVOLV7PJ.js → OERTOQSW.js} +1 -1
- package/dist/cdn/{MZPFEXP3.js → RFHHK4CN.js} +1 -1
- package/dist/cdn/{4ZSNUDGL.js → RUY3V36A.js} +50 -51
- package/dist/cdn/{RPD4TRBP.js → V32SS7PJ.js} +1 -1
- package/dist/cdn/{S2NJUN3H.js → XJN4OIMJ.js} +1 -1
- package/dist/cdn/{WYHD3EDG.js → YCAUYSSP.js} +1 -1
- package/dist/cdn/index.js +1 -1
- package/dist/docs/api.json +1 -1
- package/dist/docs/docs.json +1 -1
- package/dist/docs/vscode.html-custom-data.json +1 -1
- package/dist/docs/web-types.json +1 -1
- package/package.json +6 -6
- /package/dist/cdn/{IFER6W2B.js → OEDEKAJJ.js} +0 -0
|
@@ -1,27 +1,26 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.0/LICENSE.txt */
|
|
2
|
-
import a from"./
|
|
3
|
-
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,r){let t;if(
|
|
2
|
+
import a from"./M3HTSZRF.js";export default $arcgis.t(([mt,me,Ge,ft,{addressToLocations:yt},Be,V,Y,fe,ye,Qe,We,ge,Ke,{createRenderer:gt},{getSchemesByTag:pt,getSchemes:wt},{getBackgroundColorTheme:Ae},{createAgeRenderer:bt,createContinuousRenderer:vt},{getSchemesByTag:pe},{createContinuousRenderer:St},{createRenderer:Tt},{getSchemesByTag:xt},{createRenderer:Et},{getSchemesByTag:It},{createRenderer:Lt},{getSchemesByTag:$t},{createRenderer:Ft},{getSchemesByTag:_t},{createAgeRenderer:kt,createContinuousRenderer:Nt},{createRenderer:qt},{getSchemesByTag:At},Ue,Re,Me,P,{executeQueryStreaming:Rt},Mt,{a:Le,b:$e,c:O,d:re,e:ae,f:j,g:D,h:k,i:p,j:g,k:N,l:x,m:Fe,n:U,o:J,p:_e,q:L,r:q,s:n,t:h,u:E,v:oe,w:ke,x:C}])=>{var qe=e=>Array.isArray(e)&&e.every(O),ct=e=>typeof e=="object"&&e!=null&&"messages"in e&&qe(e.messages),dt=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,A=class extends _e{tools;handleToolErrors=!0;trace=!1;constructor(e,r){let{name:t,tags:a,handleToolErrors:o}=r??{};super({name:t,tags:a,func:(i,s)=>this.run(i,s)}),this.tools=e,this.handleToolErrors=o??this.handleToolErrors}async runTool(e,r){let t=this.tools.find(a=>a.name===e.name);try{if(t===void 0)throw new Error(`Tool "${e.name}" not found.`);let a=await t.invoke({...e,type:"tool_call"},r);return O(a)&&a.getType()==="tool"||J(a)?a:new re({status:"success",name:t.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||$e(a))throw a;return new re({status:"error",content:`Error: ${a.message}
|
|
3
|
+
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,r){let t;if(dt(e))t=[await this.runTool(e.lg_tool_call,r)];else{let i;if(qe(e))i=e;else if(ct(e))i=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(i.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),l;for(let c=i.length-1;c>=0;c-=1){let d=i[c];if(D(d)){l=d;break}}if(l==null||!D(l))throw new Error("ToolNode only accepts AIMessages as input.");t=await Promise.all(l.tool_calls?.filter(c=>c.id==null||!s.has(c.id)).map(c=>this.runTool(c,r))??[])}if(!t.some(J))return Array.isArray(e)?t:{messages:t};let a=[],o=null;for(let i of t)J(i)?i.graph===U.PARENT&&Array.isArray(i.goto)&&i.goto.every(s=>Fe(s))?o?o.goto.push(...i.goto):o=new U({graph:U.PARENT,goto:i.goto}):a.push(i):a.push(Array.isArray(e)?[i]:{messages:[i]});return o&&a.push(o),a}};var us=g.Root({llmInputMessages:g({reducer:(e,r)=>L([],r),default:()=>[]})});var Je=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
4
4
|
|
|
5
5
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
6
6
|
|
|
7
|
-
${t}`},default:()=>""}),intent:
|
|
7
|
+
${t}`},default:()=>""}),intent:g({reducer:(e,r)=>r}),vectorSearchLayerResults:g({reducer:(e,r)=>r,default:()=>[]}),vectorSearchFieldResults:g({reducer:(e,r)=>r})});async function zt(e,r){let t="https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer";console.log(`[goToAddress] Geocoding: ${e}`);let a=(await yt(t,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!a?.extent)throw new Error(`Could not find location for: ${e}`);let{xmin:o,ymin:i,xmax:s,ymax:l,spatialReference:c}=a.extent,d=new Ge({xmin:o,ymin:i,xmax:s,ymax:l,spatialReference:c}),u=(o+s)/2,m=(i+l)/2,f=new me({x:u,y:m,spatialReference:c}),y=new ft({style:"circle",color:"red",size:12}),w=new mt({geometry:f,symbol:y});return r.graphics.removeAll(),r.graphics.add(w),await r.goTo(d),`Successfully zoomed to: ${a.address}. Location coordinates: x=${u}, y=${m}, wkid=${c.wkid}`}var Ct=["mapView"];function $(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("NavigationAgent context missing");let t=Ct.filter(a=>!(a in r));if(t.length)throw new Error(`NavigationAgent context missing: ${t.join(", ")}`);return r}async function jt({address:e},r){let{mapView:t}=$(r);return await zt(e,t)}var Vt=n.object({address:n.string().describe("The full address or place name to locate.")}),Ot=p(jt,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Vt});async function Dt(e,r){let t=r.map.bookmarks;if(!t||t.length===0)throw new Error("No bookmarks found in the map.");let a=t.find(i=>i.name===e);if(!a)throw new Error(`Bookmark with name "${e}" not found.`);let o=a.viewpoint;if(!o)throw new Error(`Bookmark with name "${e}" does not have a valid viewpoint.`);return await r.goTo(o),`Navigated to bookmark: ${e}`}async function Pt({bookmarkName:e},r){let{mapView:t}=$(r);return await Promise.resolve(Dt(e,t))}var Gt=k.object({bookmarkName:k.string().describe("The name of the bookmark to navigate to.")}),Bt=p(Pt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Gt});async function Qt(e,r,t){let a=t.map?.allLayers.find(i=>i.id===e);if(!a)return`Error: Layer with id ${e} not found`;let o=a.createQuery();o.where=r??"1=1";try{let{extent:i,count:s}=await a.queryExtent(o);if(s===0)return`No features found in ${a.title} matching: ${r}`;if(i)await t.goTo(i);else return`Error: Unable to determine extent for ${a.title}`;return`Successfully zoomed to ${s} feature(s) in ${a.title}`}catch(i){return console.error("Error in goToFeatures:",i),`Error: ${i instanceof Error?i.message:"Unknown error"}`}}async function Wt({layerId:e,where:r},t){let{mapView:a}=$(t);return await Qt(e,r,a)}var Kt=k.object({layerId:k.string().describe("The layerId of the layer to zoom to."),where:k.string().describe("The sql-92 where clause used to query features to zoom to")}),Ut=p(Wt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Kt});async function Jt(e){let r=new Ge({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(r),"Successfully zoomed to world extent"}async function Ht(e,r){let{mapView:t}=$(r);return await Jt(t)}var Zt=k.object({}),Yt=p(Ht,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Zt});async function Xt(e){let r=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(r)await e.goTo(r);else throw new Error("Initial extent is undefined");return"Successfully zoomed to home extent"}async function er(e,r){let{mapView:t}=$(r);return await Xt(t)}var tr=n.object({}),rr=p(er,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:tr});async function ar(e,r){await r.when();let t=r.map?.allLayers.find(o=>o.id===e);if(!t)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),`Could not find layer for: ${e}`;console.log(`[goToLayer] Zooming to layer: ${t.title}`);let a;return(t.type==="link-chart"||t.type==="knowledge-graph-sublayer")&&r.map?.activeLinkChartLayer?a=r.map.diagramNodesExtent:a=t.fullExtent,a?(await r.goTo(a),t.visible=!0,`Successfully zoomed to: ${t.title??""}`):"Layer has no defined extent. Cannot zoom to layer."}async function or({layerId:e},r){let{mapView:t}=$(r);return await ar(e,t)}var ir=k.object({layerId:k.string().describe("The id of the layer to navigate to")}),nr=p(or,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:ir});async function sr(e,r){return await r.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function lr({scale:e},r){let{mapView:t}=$(r);return await sr(e,t)}var cr=n.object({scale:n.number().describe("The map scale of the view to go to.")}),dr=p(lr,{name:"goToScale",description:"Go to the specified view scale.",schema:cr});async function ur(e,r,t){let a={target:new me({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return t?.zoom!==void 0&&(a.zoom=t.zoom),t?.scale!==void 0&&(a.scale=t.scale),await r.goTo(a),`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,t?.zoom!==void 0?`zoom ${t.zoom}`:"",t?.scale!==void 0?`scale 1:${t.scale}`:""].filter(Boolean).join(", ")}`}async function hr({center:e,zoom:r,scale:t},a){let{mapView:o}=$(a);return await ur(e,o,{zoom:r,scale:t})}var mr=n.object({center:n.object({longitude:n.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:n.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:n.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:n.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),fr=p(hr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:mr});async function yr(e,r){return await r.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function gr({zoom:e},r){let{mapView:t}=$(r);return await yr(e,t)}var pr=n.object({zoom:n.number().min(1).max(20).describe("The zoom level of the view to go to.")}),wr=p(gr,{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:pr}),we=[Ot,Bt,Ut,Yt,rr,nr,dr,fr,wr],ze=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./QZJ4SRT5.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./BN4IYD74.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./M32BWJ4D.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./GXFH7ZNV.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./G65WIFNI.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./WE5QPXDZ.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./XOLWLHTD.js").then(e=>e.default),"../agents/layerFilter/prompts/layer_filter_prompt.md":()=>import("./Y4325EIX.js").then(e=>e.default),"../agents/layerQuery/prompts/data_query_prompt.md":()=>import("./3YA7AYJB.js").then(e=>e.default),"../agents/layerQuery/prompts/summarize_query_response_prompt.md":()=>import("./JVPRUGML.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./TBTPT64L.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./LDS4EYQM.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./IMPD5HA4.js").then(e=>e.default)});async function F(e){let r=Object.entries(ze).find(([t])=>t.endsWith(`/${e}.md`));if(console.log(`entry for prompt "${e}":`,r),!r)throw new Error(`Prompt not found: ${e}
|
|
8
8
|
Available prompts:
|
|
9
9
|
${Object.keys(ze).join(`
|
|
10
|
-
`)}`);return await r[1]()}var
|
|
10
|
+
`)}`);return await r[1]()}var br=(e,r=3)=>e.filter(t=>t instanceof ae).slice(-r),v=(e,r=3)=>{let t=e.map((o,i)=>o instanceof ae?i:-1).filter(o=>o!==-1);if(t.length===0)return[];let a=t.length>r?t[t.length-r]:t[0];return e.slice(a)},_=(e,r=" ")=>br(e).map(t=>t.content).join(r).trim();async function vr(e,r){let t=await F("navigation_tool_prompt"),{mapView:a}=$(r),o=a.map,i=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((w,S)=>`${S+1}. layerId=${w.id} | title=${w.title??""} | name=${w.name??""} | score=${w.score.toFixed(2)}`).join(`
|
|
11
11
|
`):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",l=e.intent==="goToBookmark"&&o.bookmarks?.length?`Available bookmarks:
|
|
12
12
|
${JSON.stringify(o.bookmarks,null,2)}`:"",c=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
|
|
13
13
|
${i}`:"",d=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
|
|
14
|
-
${s}`:"",u={intent:e.intent,bookmarksSection:l,layersSection:c,fieldsSection:d,currentZoom:a.zoom},m=await C({promptText:t,messages:
|
|
15
|
-
`);
|
|
16
|
-
`)
|
|
14
|
+
${s}`:"",u={intent:e.intent,bookmarksSection:l,layersSection:c,fieldsSection:d,currentZoom:a.zoom},m=await C({promptText:t,messages:v(e.messages),inputVariables:u,tools:we}),f=[...e.messages,m],y=(m.tool_calls?.length??0)>0?[...f]:[...f,m];return{...e,messages:y}}async function Sr(e,r){let t=await new A(we).invoke({messages:v(e.messages)},r),a=t.messages.map(s=>s.text).join(`
|
|
15
|
+
`);await h({text:`Finished executing navigation tool: ${a}`},r);let o=[...e.messages,...t.messages],i=t.messages.map(s=>s.text).join(`
|
|
16
|
+
`);return{...e,messages:o,outputMessage:i}}async function Tr(e){let r=await F("navigation_intent_prompt"),t={tools:we.map(s=>({name:s.name,description:s.description,schema:s.schema})).map(({name:s,description:l,schema:c})=>`${s}: ${l}, ${JSON.stringify(c)}`).join(`
|
|
17
|
+
`)},a=n.object({intent:n.string()}),o=await ke({promptText:r,modelTier:"fast",messages:v(e.messages),inputVariables:t,schema:a}),i=typeof o.intent=="string"?o.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:i||""}}var b=(e,r)=>{let t=e?.configurable?.services?.[r];if(t==null)throw new Error(`${r} missing in config.configurable.services`);return t},xr=.7,Er=async(e,r)=>{try{let t=_(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=(await a.searchLayers({text:t,minScore:xr,embeddingCache:i})).map(({id:c,score:d})=>{let u=o.get(c)?.layerItem;return{id:c,title:u?.title,name:u?.name??void 0,score:d}}),l;return s.length>0?l=`Vector search completed. Matching layers:
|
|
17
18
|
${s.map(c=>`- layerId=${c.id} | title=${c.title??""} | name=${c.name??""} | score=${c.score.toFixed(2)}`).join(`
|
|
18
|
-
`)}`:l="Vector search completed. No matching layers found.",await h({text:l},r),{...e,vectorSearchLayerResults:s}}catch(t){throw await h({text:`Error during vector search layers: ${t instanceof Error?t.message:String(t)}`},r),t}},Ce=.7
|
|
19
|
+
`)}`:l="Vector search completed. No matching layers found.",await h({text:l},r),{...e,vectorSearchLayerResults:s}}catch(t){throw await h({text:`Error during vector search layers: ${t instanceof Error?t.message:String(t)}`},r),t}},Ce=.7,Ir=10,Lr=async(e,r)=>{try{let t=_(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=e.vectorSearchLayerResults?.map(d=>d.id)??[];if(s.length===0)return await h({text:"No candidate layers for field search"},r),e;let l=(await a.searchFields({text:t,layerIds:s,minScore:Ce,topResults:Ir,embeddingCache:i})).map(({layerId:d,results:u})=>{let m=o.get(d)?.fieldRegistry;return{layerId:d,layerName:o.get(d)?.layerItem.name,results:u.map(f=>{let y=m?.get(f.name);return{name:f.name,score:f.score,type:y?.type,alias:y?.alias,description:y?.description,statistics:y?.statistics}})}}),c;return l.length>0?c=`Vector search completed. Matching layers and fields:
|
|
19
20
|
${l.map(d=>`${d.layerName??d.layerId}:
|
|
20
21
|
${d.results.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
|
|
21
22
|
`)}`).join(`
|
|
22
|
-
`)}`:c=`No vector search field results found for score over ${Ce}.`,await h({text:c},r),{...e,vectorSearchFieldResults:l}}catch(t){throw await h({text:`Error during vector search fields: ${t instanceof Error?t.message:String(t)}`},r),t}},B=(e,r)=>(t,a)=>{let o=a?.configurable?.services;for(let i of e)if(!o?.[i])throw new Error(`${r} requires services.${i} to be available.`);return t}
|
|
23
|
-
`)].join(`
|
|
24
|
-
`),s={agentId:je.id,id:"selectLocation",kind:"singleSelection",message:i,metadata:t};throw new re(s)};async function Rr(e,r){if(!e.extent)throw new Error(`No extent available for location: ${e.address}`);let{xmin:t,ymin:a,xmax:o,ymax:i,spatialReference:s}=e.extent,l=new Be({xmin:t,ymin:a,xmax:o,ymax:i,spatialReference:s}),c=(t+o)/2,d=(a+i)/2,u=new fe({x:c,y:d,spatialReference:s}),m=new yt({style:"circle",color:"red",size:10}),f=new gt({geometry:u,symbol:m});return r.graphics.removeAll(),r.graphics.add(f),await r.goTo(l),`Successfully zoomed to: ${e.address}. Location coordinates: x=${c}, y=${d}, wkid=${s.wkid}`}var Ar=async(e,r)=>{let{selectedLocation:t}=e;if(!t)return{outputMessage:"No location selected."};let{mapView:a}=$(r);return{outputMessage:await Rr(t,a),geocodeResults:null,selectedLocation:null}},qr=()=>new R(Je).addNode("requireNavigationServices",_r).addNode("intentLLM",Er).addNode("vectorSearchLayers",Lr).addNode("vectorSearchFields",Fr).addNode("agent",Sr).addNode("tools",Tr).addNode("locationHITL",kr).addNode("zoomToSelectedLocation",Ar).addEdge(k,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addConditionalEdges("tools",e=>e.geocodeResults&&e.geocodeResults.length>0?"locationHITL":"end",{locationHITL:"locationHITL",end:v}).addConditionalEdges("locationHITL",e=>e.selectedLocation?"zoomToSelectedLocation":"end",{zoomToSelectedLocation:"zoomToSelectedLocation",end:v}).addEdge("zoomToSelectedLocation",v),Mr=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
23
|
+
`)}`:c=`No vector search field results found for score over ${Ce}.`,await h({text:c},r),{...e,vectorSearchFieldResults:l}}catch(t){throw await h({text:`Error during vector search fields: ${t instanceof Error?t.message:String(t)}`},r),t}},B=(e,r)=>(t,a)=>{let o=a?.configurable?.services;for(let i of e)if(!o?.[i])throw new Error(`${r} requires services.${i} to be available.`);return t},$r=(e,r)=>B(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,r),Fr=()=>new q(Je).addNode("requireNavigationServices",$r).addNode("intentLLM",Tr).addNode("vectorSearchLayers",Er).addNode("vectorSearchFields",Lr).addNode("agent",vr).addNode("tools",Sr).addEdge(N,"requireNavigationServices").addEdge("requireNavigationServices","intentLLM").addConditionalEdges("intentLLM",e=>e.intent==="goToLayer"||e.intent==="goToFeatures"?"vectorSearchLayers":"agent",{vectorSearchLayers:"vectorSearchLayers",agent:"agent"}).addConditionalEdges("vectorSearchLayers",e=>e.intent==="goToFeatures"?"vectorSearchFields":"agent",{vectorSearchFields:"vectorSearchFields",agent:"agent"}).addEdge("vectorSearchFields","agent").addEdge("agent","tools").addEdge("tools",x),_r=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
25
24
|
This includes zooming, panning, centering, or geocoding based on user input. The agent is designed to handle explicit map movement requests. NOTE: DO NOT call this agent if the user asks "where is... " or "show me...", that is meant to be handled by another agent.
|
|
26
25
|
|
|
27
26
|
Supported actions:
|
|
@@ -40,19 +39,19 @@ ${d.results.map(u=>` - ${u.name} (${u.score.toFixed(2)})`).join(`
|
|
|
40
39
|
_Example: “Center the map on San Francisco at scale 50000”_
|
|
41
40
|
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
42
41
|
_Example: “Go to the Downtown bookmark”_
|
|
43
|
-
_Example: “Zoom to 1600 Pennsylvania Ave”_`,
|
|
42
|
+
_Example: “Zoom to 1600 Pennsylvania Ave”_`,hl={id:"navigation",name:"Navigation Agent",description:_r,createGraph:Fr,workspace:Je},He=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
44
43
|
|
|
45
44
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
46
45
|
|
|
47
|
-
${t}`},default:()=>""}),vectorSearchLayerIds:y(),vectorSearchFieldResults:y(),layerFieldInfo:y(),queryResponse:y()}),zr=async(e,r)=>(await h({text:"Exiting Data Exploration agent"},r),e),Q=async(e,r)=>{let t=e.tool_calls??[];if(t.length===0){await h({text:`LLM did not request any tool calls: ${String(e?.content)}`},r);return}await Promise.all(t.map(async a=>await h({text:`LLM requested tool call with arguments: ${JSON.stringify(a.args,null,2)}`},r))),console.log("LLM response:",JSON.stringify(e.tool_calls,null,2))},ve=async(e,r,t)=>{let a=e.map?.allLayers.find(i=>i.id===r),o=a.createQuery();o.where=t??"1=1";try{let{extent:i,count:s}=await a.queryExtent(o);return!i||s===0?{success:!1,error:`No features found for where clause: ${t}`}:(await e.goTo(i),{success:!0})}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}},Cr=async(e,r,t)=>{let a=t.map?.allLayers.find(s=>s.id===e);if(!a)return`Could not find layer with ID: ${e}`;a.definitionExpression=r,a.visible=!0;let o=await ve(t,e,r),i=a.title??a.layerId;return o.success?`Applied definition expression to layer "${a.title??e}": ${r}`:`Applied filter to "${i}" but no features matched. ${o.error}`},jr=["mapView"];function q(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("DataExplorationAgent context missing");let t=jr.filter(a=>!(a in r));if(t.length)throw new Error(`DataExplorationAgent context missing: ${t.join(", ")}`);return r}var Vr=async({layerId:e,definitionExpression:r},t)=>{let{mapView:a}=q(t);return await Cr(e,r,a)},Or=n.object({layerId:n.string().describe("The layerId of the layer on which to set a definitionExpression."),definitionExpression:n.string().describe("The SQL-92 where clause used to set a definition expression on the layer.")}),Dr=p(Vr,{name:"setDefinitionExpression",description:"Set a SQL-92 where clause to the definition expression of a layer (i.e. a server-side filter). This filters features at the server level, affecting all views of the layer. Do not prioritize this tool unless specifically asked for or implied for server level, affecting all views of the layer.",schema:Or});function le(e){return"point"in e&&e.point!==void 0}function ce(e){return"layerId"in e&&e.layerId!==void 0}var W=async(e,r)=>{if(le(e)){let{point:t}=e;return{geometry:new fe({x:t.x,y:t.y,spatialReference:t.spatialReference?{wkid:t.spatialReference.wkid}:r.spatialReference})}}if(ce(e)){let t=r.map?.allLayers.find(a=>a.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};try{let a=await t.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:r.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=Y.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return o.spatialReference||(o.spatialReference=r.spatialReference),{geometry:o}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},Pr=async(e,r,t,a,o)=>{let i=r.map?.allLayers.find(d=>d.id===e.layerId);if(!i)return`Could not find target layer with ID: ${e.layerId}`;let s;if(o){let d=await W(o,r);if("error"in d)return d.error;s=d.geometry}i.featureEffect=null,i.featureEffect=new Qe({filter:new V({where:e.where,geometry:s,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),i.visible=!0;let l=await ve(r,o?o.layerId:e.layerId,o?o.where:e.where),c=i.title??e.layerId;return l.success?`Applied feature effects to target layer "${i.title??e.layerId}"${o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},Gr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],M=n.enum(Gr),Br=async({targetLayer:e,geometryLayer:r,includedEffect:t="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},o)=>{let{mapView:i}=q(o);return await Pr(e,i,t,a,r)},Qr=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a feature effect."),where:n.string().describe("The SQL-92 where clause representing the features to emphasize.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:M.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),includedEffect:n.string().optional().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:n.string().optional().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.")}),Wr=p(Br,{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:Qr}),Kr=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId);if(!a)return`Could not find target layer with ID: ${e.layerId}`;let o;if(t){let c=await W(t,r);if("error"in c)return c.error;o=c.geometry}let i=await r.whenLayerView(a);i.filter=null,i.filter=new V({where:e.where,geometry:o,spatialRelationship:"intersects",distance:t?.distance,units:t?.units}),a.visible=!0;let s=await ve(r,t?t.layerId:e.layerId,t?t.where:e.where),l=a.title??e.layerId;return s.success?`Applied feature filter to layer "${a.title??e.layerId}"${t?` using geometry from layer "${t.layerId}"`:""}.`:`Applied filter to "${l}" but no features matched. ${s.error}`},Ur=async({targetLayer:e,geometryLayer:r},t)=>{let{mapView:a}=q(t);return await Kr(e,a,r)},Hr=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a filter."),where:n.string().describe("The SQL-92 where clause representing the features to display.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:M.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Jr=p(Ur,{name:"setFeatureFilter",description:"Sets a client-side filter using a where clause, geometry filter, or both on a target layer. This filters features at the client level in the view.",schema:Hr}),de=(e,r,t)=>{if(e&&typeof e!="function"){let a="getField"in t&&t.getField?.(e),o=a&&"getFieldDomain"in t&&t.getFieldDomain?t.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let i=o.codedValues.find(s=>s.code===r);return i?i.name:null}}return null},Zr=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},Yr=async(e,r,t,a)=>{let o=a.map?.allLayers.find(d=>d.id===e),i=Zr(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null,c=de(r,l,o)||l;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${c}`,details:{fieldName:r,value:c,where:t.where}}};async function Xr({layerId:e,fieldName:r,query:t},a){let{mapView:o}=q(a),i=await Yr(e,r,t,o);return JSON.stringify(i,null,2)}var ea=n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:n.string().describe("The name of the field/attribute from which to get a field value."),query:n.object({where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),ta=p(Xr,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:ea}),Se=(e,r)=>r?e.hasAllFeaturesInView:e.hasAllFeatures,ra=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryLayer:s}=e,l=o.map?.allLayers.find(x=>x.id===r.layerId);if(!l)throw new Error(`Layer '${r.layerId}' not found.`);let c=await o.whenLayerView(l),d=i.get(r.layerId)?.fieldRegistry.get(t);if(!d)throw new Error(`Field '${t}' not found.`);let u,m;if(s){let x=await W(s,o);if("error"in x)throw new Error(x.error);if(!x.geometry)throw new Error(`No features found matching: ${s.where}`);u={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0},m=new V({geometry:x.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let f=Se(c,!1),g=null,b=null,T=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{g=await ge({layer:l,useFeaturesInView:f,view:f?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m},outStatisticTypes:{include:[a]}}),["string","small-integer","integer"].includes(d.type)&&(b=(await ye({layer:l,useFeaturesInView:f,view:f?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m}})).uniqueValueInfos.sort((x,z)=>z.count-x.count).slice(0,T))}catch(x){console.error("Statistics error:",x)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof g?.[a]=="number"?g[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:g?.[a]??null,summaryStatistics:g,uniqueValues:b,where:r.where,spatialFilterInfo:u}}};async function aa({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=w(o,"layersAndFieldsRegistry"),{mapView:s}=q(o),l=await ra({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return JSON.stringify(l,null,2)}var oa=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryLayer:n.union([n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:M.optional().describe("The units used to query by geometry and distance.")}),n.object({}).strict()]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),fieldName:n.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:n.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),ia=p(aa,{name:"getStatistics",description:'Returns one or more summary statistics for the given field. Statistic types include: count, maximum, minimum, average, median, standard deviation, variance, mode, sum, nullcount (number of features without a value for a given field), unique values. For "most common/frequent" questions: Use statisticType "count" on a categorical field. The response includes uniqueValues sorted by frequency (most common first). Statistics can be returned for number, date, and string fields. Also returns frequency analysis for string fields - unique values sorted by occurrence count (most frequent first). Use this for "most common", "most frequent", or "how many of each" questions. Only call this tool when the question requires filtering (e.g. a WHERE clause or spatial constraint) that cannot be satisfied by precomputed stats.',schema:oa}),na=async(e,r,t,a)=>{let o=t.map?.allLayers.find(u=>u.id===e.layerId),i=await t.whenLayerView(o),s=o.title??e.layerId,l;if(a){let u=await W(a,t);if("error"in u)return{tool:"getTopFeatures",layerName:s,summary:"Geometry lookup failed",details:{error:u.error}};if(!u.geometry)return{tool:"getTopFeatures",layerName:s,summary:"No features found for geometry filter",details:{error:`No features found matching: ${a.where}`}};l=u.geometry}let c=e.outFields.length>2?e.outFields:["*"],d=r.groupByFields&&r.groupByFields.length>0;try{let u;if(d){let f=new We({where:e.where||"1=1",outFields:c,orderByFields:e.orderByFields,geometry:l,spatialRelationship:l?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Ke({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})});u=await o.queryTopFeatures(f)}else{let f=new pe({where:e.where||"1=1",outFields:c,orderByFields:r.orderByFields,num:r.topCount,geometry:l,spatialRelationship:l?"intersects":void 0,distance:a?.distance,units:a?.units,outSpatialReference:t.spatialReference}),g=Se(i,!1);try{u=g?await i.queryFeatures(f):await o.queryFeatures(f)}catch(b){console.warn("Client-side query failed, falling back to server:",b),u=await o.queryFeatures(f)}}let m=u.features.map(f=>f.attributes);return{tool:"getTopFeatures",layerName:s,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,attributes:m,where:e.where,orderByFields:r.orderByFields,...d&&{groupByFields:r.groupByFields}}}}catch(u){return{tool:"getTopFeatures",layerName:s,summary:"Query failed",details:{error:u instanceof Error?u.message:String(u)}}}},sa=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=q(a),i=await na(e,r,o,t);return JSON.stringify(i,null,2)},la=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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("*"))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:M.describe("The units used to query by geometry and distance.").optional()}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),topFilter:n.object({topCount:n.number().describe("Number of top features to return per group."),orderByFields:n.array(n.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:n.array(n.string().describe("Field(s) to group results by. Returns top N per group."))})}),ca=p(sa,{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:la}),se=25,da=async(e,r,t,a)=>{let o=r.map?.allLayers.find(g=>g.id===e.layerId),i=await r.whenLayerView(o),s=o.title??e.layerId,l;if(t){let g=await W(t,r);if("error"in g){let b={error:g.error};return ce(t)?(b.geometryLayerId=t.layerId,b.geometryWhere=t.where):le(t)&&(b.point=t.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:b}}if(!g.geometry){let b={};return ce(t)?(b.error=`No features found matching: ${t.where}`,b.geometryLayerId=t.layerId,b.geometryWhere=t.where):le(t)&&(b.error="Failed to create point geometry",b.point=t.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:b}}l=g.geometry}else a&&(l=r.extent.clone());let c=Se(i,a??!1),d=new pe({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,...l&&{geometry:l,spatialRelationship:"intersects"},...t?.distance&&{distance:t.distance},...t?.units&&{units:t.units},outSpatialReference:r.spatialReference}),u,m;try{u=c?await i.queryFeatureCount(d):await o.queryFeatureCount(d),u>0&&u<=se&&(m=c?await i.queryFeatures(d):await o.queryFeatures(d),m&&m.features.forEach(g=>{let b=g.attributes;o.fields.forEach(T=>{let x=b[T.name],z=de(T.name,x,o);z&&(b[T.name]=z)})}))}catch(g){console.warn("Client-side query failed, falling back to server:",g),u=await o.queryFeatureCount(d),u>0&&u<=se&&(m=await o.queryFeatures(d),m&&m.features.forEach(b=>{o.fields.forEach(T=>{let x=b.attributes[T.name],z=de(T.name,x,o);z&&(b.attributes[T.name]=z)})}))}let f=m?.features.map(g=>g.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,...f&&{attributes:f},...u>se&&{note:`${u} features found. Too many to list. Use filters to narrow results.`}}}};async function ua({targetLayer:e,geometryFilter:r,useCurrentExtent:t},a){let{mapView:o}=q(a),i=await da(e,o,r,t);return JSON.stringify(i,null,2)}var ha=n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:n.number().optional().describe("The buffer distance around the geometry."),units:M.optional().describe("The units for the distance buffer.")}),ma=n.object({point:n.object({x:n.number().describe("X coordinate (longitude) from navigation result"),y:n.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:n.object({wkid:n.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:n.number().optional().describe("Optional buffer distance around the point."),units:M.optional().describe("The units for the distance buffer.")}),fa=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.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:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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:n.union([ha,ma]).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:n.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).")}),ga=p(ua,{name:"queryFeatures",description:"Queries features from a layer. Returns count and attributes (if \u226425 features). Use for listing features, finding features matching conditions, or spatial queries.",schema:fa}),Ye=[ta,ia,ca,ga],Xe=[Dr,Wr,Jr],X=()=>{let e=new Date().getTimezoneOffset(),r=e<=0?"+":"-",t=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${r}${t}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},ya=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await F("data_explore_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:S(e.messages),inputVariables:i,tools:Xe}),l=[...e.messages,s],c=(s.tool_calls?.length??0)>0?l:[...l,s],d=s.content.toString();return await Q(s,r),{...e,messages:c,outputMessage:d}},pa=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("data_explore_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:S(e.messages),inputVariables:i,tools:Ye}),l=[...e.messages,s],c=s.content.toString();return await Q(s,r),{...e,messages:l,outputMessage:c}},wa=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await F("summarize_query_response_prompt"),a={queryResponse:e.queryResponse},o=await ie({promptText:t,messages:S(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content,s=new j(i);return await h({text:`Received response from LLM: ${i}`},r),{...e,outputMessage:i,messages:[...e.messages,s]}}catch(t){throw await h({text:"Error during filter LLM request"},r),new Error(`Error during filter LLM request: ${t instanceof Error?t.message:String(t)}`)}};async function ba(e,r){let t=await new A(Xe).invoke({messages:S(e.messages)},r),a=[...e.messages,...t.messages],o=t.messages.map(l=>new j({content:l.content,additional_kwargs:l.additional_kwargs}));await h({text:`Finished executing layer filter tool: ${t.messages.map(l=>l.content).join(", ")}`},r);let i=[...a,...o],s=o.map(l=>l.content).join(`
|
|
46
|
+
${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g()}),kr=async(e,r)=>(await h({text:"Exiting Data Exploration agent"},r),e),Q=async(e,r)=>{let t=e.tool_calls??[];if(t.length===0){await h({text:`LLM did not request any tool calls: ${String(e?.content)}`},r);return}await Promise.all(t.map(async a=>await h({text:`LLM requested tool call with arguments: ${JSON.stringify(a.args,null,2)}`},r))),console.log("LLM response:",JSON.stringify(e.tool_calls,null,2))},be=async(e,r,t)=>{let a=e.map?.allLayers.find(i=>i.id===r),o=a.createQuery();o.where=t??"1=1";try{let{extent:i,count:s}=await a.queryExtent(o);return!i||s===0?{success:!1,error:`No features found for where clause: ${t}`}:(await e.goTo(i),{success:!0})}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}},Nr=async(e,r,t)=>{let a=t.map?.allLayers.find(s=>s.id===e);if(!a)return`Could not find layer with ID: ${e}`;a.definitionExpression=r,a.visible=!0;let o=await be(t,e,r),i=a.title??a.layerId;return o.success?`Applied definition expression to layer "${a.title??e}": ${r}`:`Applied filter to "${i}" but no features matched. ${o.error}`},qr=["mapView"];function R(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("DataExplorationAgent context missing");let t=qr.filter(a=>!(a in r));if(t.length)throw new Error(`DataExplorationAgent context missing: ${t.join(", ")}`);return r}var Ar=async({layerId:e,definitionExpression:r},t)=>{let{mapView:a}=R(t);return await Nr(e,r,a)},Rr=n.object({layerId:n.string().describe("The layerId of the layer on which to set a definitionExpression."),definitionExpression:n.string().describe("The SQL-92 where clause used to set a definition expression on the layer.")}),Mr=p(Ar,{name:"setDefinitionExpression",description:"Set a SQL-92 where clause to the definition expression of a layer (i.e. a server-side filter). This filters features at the server level, affecting all views of the layer. Do not prioritize this tool unless specifically asked for or implied for server level, affecting all views of the layer.",schema:Rr});function se(e){return"point"in e&&e.point!==void 0}function le(e){return"layerId"in e&&e.layerId!==void 0}var W=async(e,r)=>{if(se(e)){let{point:t}=e;return{geometry:new me({x:t.x,y:t.y,spatialReference:t.spatialReference?{wkid:t.spatialReference.wkid}:r.spatialReference})}}if(le(e)){let t=r.map?.allLayers.find(a=>a.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};try{let a=await t.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:r.spatialReference});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=Y.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return o.spatialReference||(o.spatialReference=r.spatialReference),{geometry:o}}catch(a){return{error:`Failed to query geometry: ${String(a)}`}}}return{error:"Invalid geometry configuration provided"}},zr=async(e,r,t,a,o)=>{let i=r.map?.allLayers.find(d=>d.id===e.layerId);if(!i)return`Could not find target layer with ID: ${e.layerId}`;let s;if(o){let d=await W(o,r);if("error"in d)return d.error;s=d.geometry}i.featureEffect=null,i.featureEffect=new Be({filter:new V({where:e.where,geometry:s,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),i.visible=!0;let l=await be(r,o?o.layerId:e.layerId,o?o.where:e.where),c=i.title??e.layerId;return l.success?`Applied feature effects to target layer "${i.title??e.layerId}"${o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${c}" but no features matched. ${l.error}`},Cr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],M=n.enum(Cr),jr=async({targetLayer:e,geometryLayer:r,includedEffect:t="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},o)=>{let{mapView:i}=R(o);return await zr(e,i,t,a,r)},Vr=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a feature effect."),where:n.string().describe("The SQL-92 where clause representing the features to emphasize.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:M.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),includedEffect:n.string().optional().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:n.string().optional().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.")}),Or=p(jr,{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:Vr}),Dr=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId);if(!a)return`Could not find target layer with ID: ${e.layerId}`;let o;if(t){let c=await W(t,r);if("error"in c)return c.error;o=c.geometry}let i=await r.whenLayerView(a);i.filter=null,i.filter=new V({where:e.where,geometry:o,spatialRelationship:"intersects",distance:t?.distance,units:t?.units}),a.visible=!0;let s=await be(r,t?t.layerId:e.layerId,t?t.where:e.where),l=a.title??e.layerId;return s.success?`Applied feature filter to layer "${a.title??e.layerId}"${t?` using geometry from layer "${t.layerId}"`:""}.`:`Applied filter to "${l}" but no features matched. ${s.error}`},Pr=async({targetLayer:e,geometryLayer:r},t)=>{let{mapView:a}=R(t);return await Dr(e,a,r)},Gr=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a filter."),where:n.string().describe("The SQL-92 where clause representing the features to display.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:M.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Br=p(Pr,{name:"setFeatureFilter",description:"Sets a client-side filter using a where clause, geometry filter, or both on a target layer. This filters features at the client level in the view.",schema:Gr}),ce=(e,r,t)=>{if(e&&typeof e!="function"){let a="getField"in t&&t.getField?.(e),o=a&&"getFieldDomain"in t&&t.getFieldDomain?t.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let i=o.codedValues.find(s=>s.code===r);return i?i.name:null}}return null},Qr=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},Wr=async(e,r,t,a)=>{let o=a.map?.allLayers.find(d=>d.id===e),i=Qr(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null,c=ce(r,l,o)||l;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${c}`,details:{fieldName:r,value:c,where:t.where}}};async function Kr({layerId:e,fieldName:r,query:t},a){let{mapView:o}=R(a),i=await Wr(e,r,t,o);return JSON.stringify(i,null,2)}var Ur=n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:n.string().describe("The name of the field/attribute from which to get a field value."),query:n.object({where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),Jr=p(Kr,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:Ur}),ve=(e,r)=>r?e.hasAllFeaturesInView:e.hasAllFeatures,Hr=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryLayer:s}=e,l=o.map?.allLayers.find(T=>T.id===r.layerId);if(!l)throw new Error(`Layer '${r.layerId}' not found.`);let c=await o.whenLayerView(l),d=i.get(r.layerId)?.fieldRegistry.get(t);if(!d)throw new Error(`Field '${t}' not found.`);let u,m;if(s){let T=await W(s,o);if("error"in T)throw new Error(T.error);if(!T.geometry)throw new Error(`No features found matching: ${s.where}`);u={geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0},m=new V({geometry:T.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let f=ve(c,!1),y=null,w=null,S=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{y=await fe({layer:l,useFeaturesInView:f,view:f?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m},outStatisticTypes:{include:[a]}}),["string","small-integer","integer"].includes(d.type)&&(w=(await ye({layer:l,useFeaturesInView:f,view:f?o:void 0,field:t,sqlWhere:r.where,...m&&{filter:m}})).uniqueValueInfos.sort((T,z)=>z.count-T.count).slice(0,S))}catch(T){console.error("Statistics error:",T)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof y?.[a]=="number"?y[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:y?.[a]??null,summaryStatistics:y,uniqueValues:w,where:r.where,spatialFilterInfo:u}}};async function Zr({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=b(o,"layersAndFieldsRegistry"),{mapView:s}=R(o),l=await Hr({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return JSON.stringify(l,null,2)}var Yr=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryLayer:n.union([n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:M.optional().describe("The units used to query by geometry and distance.")}),n.object({}).strict()]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),fieldName:n.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:n.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),Xr=p(Zr,{name:"getStatistics",description:'Returns one or more summary statistics for the given field. Statistic types include: count, maximum, minimum, average, median, standard deviation, variance, mode, sum, nullcount (number of features without a value for a given field), unique values. For "most common/frequent" questions: Use statisticType "count" on a categorical field. The response includes uniqueValues sorted by frequency (most common first). Statistics can be returned for number, date, and string fields. Also returns frequency analysis for string fields - unique values sorted by occurrence count (most frequent first). Use this for "most common", "most frequent", or "how many of each" questions. Only call this tool when the question requires filtering (e.g. a WHERE clause or spatial constraint) that cannot be satisfied by precomputed stats.',schema:Yr}),ea=async(e,r,t,a)=>{let o=t.map?.allLayers.find(u=>u.id===e.layerId),i=await t.whenLayerView(o),s=o.title??e.layerId,l;if(a){let u=await W(a,t);if("error"in u)return{tool:"getTopFeatures",layerName:s,summary:"Geometry lookup failed",details:{error:u.error}};if(!u.geometry)return{tool:"getTopFeatures",layerName:s,summary:"No features found for geometry filter",details:{error:`No features found matching: ${a.where}`}};l=u.geometry}let c=e.outFields.length>2?e.outFields:["*"],d=r.groupByFields&&r.groupByFields.length>0;try{let u;if(d){let f=new Qe({where:e.where||"1=1",outFields:c,orderByFields:e.orderByFields,geometry:l,spatialRelationship:l?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new We({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})});u=await o.queryTopFeatures(f)}else{let f=new ge({where:e.where||"1=1",outFields:c,orderByFields:r.orderByFields,num:r.topCount,geometry:l,spatialRelationship:l?"intersects":void 0,distance:a?.distance,units:a?.units,outSpatialReference:t.spatialReference}),y=ve(i,!1);try{u=y?await i.queryFeatures(f):await o.queryFeatures(f)}catch(w){console.warn("Client-side query failed, falling back to server:",w),u=await o.queryFeatures(f)}}let m=u.features.map(f=>f.attributes);return{tool:"getTopFeatures",layerName:s,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,attributes:m,where:e.where,orderByFields:r.orderByFields,...d&&{groupByFields:r.groupByFields}}}}catch(u){return{tool:"getTopFeatures",layerName:s,summary:"Query failed",details:{error:u instanceof Error?u.message:String(u)}}}},ta=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=R(a),i=await ea(e,r,o,t);return JSON.stringify(i,null,2)},ra=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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("*"))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:M.describe("The units used to query by geometry and distance.").optional()}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),topFilter:n.object({topCount:n.number().describe("Number of top features to return per group."),orderByFields:n.array(n.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:n.array(n.string().describe("Field(s) to group results by. Returns top N per group."))})}),aa=p(ta,{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:ra}),ne=25,oa=async(e,r,t,a)=>{let o=r.map?.allLayers.find(y=>y.id===e.layerId),i=await r.whenLayerView(o),s=o.title??e.layerId,l;if(t){let y=await W(t,r);if("error"in y){let w={error:y.error};return le(t)?(w.geometryLayerId=t.layerId,w.geometryWhere=t.where):se(t)&&(w.point=t.point),{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:w}}if(!y.geometry){let w={};return le(t)?(w.error=`No features found matching: ${t.where}`,w.geometryLayerId=t.layerId,w.geometryWhere=t.where):se(t)&&(w.error="Failed to create point geometry",w.point=t.point),{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:w}}l=y.geometry}else a&&(l=r.extent.clone());let c=ve(i,a??!1),d=new ge({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,...l&&{geometry:l,spatialRelationship:"intersects"},...t?.distance&&{distance:t.distance},...t?.units&&{units:t.units},outSpatialReference:r.spatialReference}),u,m;try{u=c?await i.queryFeatureCount(d):await o.queryFeatureCount(d),u>0&&u<=ne&&(m=c?await i.queryFeatures(d):await o.queryFeatures(d),m&&m.features.forEach(y=>{let w=y.attributes;o.fields.forEach(S=>{let T=w[S.name],z=ce(S.name,T,o);z&&(w[S.name]=z)})}))}catch(y){console.warn("Client-side query failed, falling back to server:",y),u=await o.queryFeatureCount(d),u>0&&u<=ne&&(m=await o.queryFeatures(d),m&&m.features.forEach(w=>{o.fields.forEach(S=>{let T=w.attributes[S.name],z=ce(S.name,T,o);z&&(w.attributes[S.name]=z)})}))}let f=m?.features.map(y=>y.attributes);return{tool:"queryFeatures",layerName:s,summary:`${u} features found`,details:{totalCount:u,where:e.where,...f&&{attributes:f},...u>ne&&{note:`${u} features found. Too many to list. Use filters to narrow results.`}}}};async function ia({targetLayer:e,geometryFilter:r,useCurrentExtent:t},a){let{mapView:o}=R(a),i=await oa(e,o,r,t);return JSON.stringify(i,null,2)}var na=n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:n.number().optional().describe("The buffer distance around the geometry."),units:M.optional().describe("The units for the distance buffer.")}),sa=n.object({point:n.object({x:n.number().describe("X coordinate (longitude) from navigation result"),y:n.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:n.object({wkid:n.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:n.number().optional().describe("Optional buffer distance around the point."),units:M.optional().describe("The units for the distance buffer.")}),la=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.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:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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:n.union([na,sa]).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:n.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).")}),ca=p(ia,{name:"queryFeatures",description:"Queries features from a layer. Returns count and attributes (if \u226425 features). Use for listing features, finding features matching conditions, or spatial queries.",schema:la}),Ze=[Jr,Xr,aa,ca],Ye=[Mr,Or,Br],X=()=>{let e=new Date().getTimezoneOffset(),r=e<=0?"+":"-",t=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${r}${t}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},da=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await F("data_explore_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:v(e.messages),inputVariables:i,tools:Ye}),l=[...e.messages,s],c=(s.tool_calls?.length??0)>0?l:[...l,s],d=s.content.toString();return await Q(s,r),{...e,messages:c,outputMessage:d}},ua=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("data_explore_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:v(e.messages),inputVariables:i,tools:Ze}),l=[...e.messages,s],c=s.content.toString();return await Q(s,r),{...e,messages:l,outputMessage:c}},ha=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await F("summarize_query_response_prompt"),a={queryResponse:e.queryResponse},o=await oe({promptText:t,messages:v(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content,s=new j(i);return await h({text:`Received response from LLM: ${i}`},r),{...e,outputMessage:i,messages:[...e.messages,s]}}catch(t){throw await h({text:"Error during filter LLM request"},r),new Error(`Error during filter LLM request: ${t instanceof Error?t.message:String(t)}`)}};async function ma(e,r){let t=await new A(Ye).invoke({messages:v(e.messages)},r),a=[...e.messages,...t.messages],o=t.messages.map(l=>new j({content:l.content,additional_kwargs:l.additional_kwargs}));await h({text:`Finished executing layer filter tool: ${t.messages.map(l=>l.content).join(", ")}`},r);let i=[...a,...o],s=o.map(l=>l.content).join(`
|
|
48
47
|
|
|
49
|
-
`);return{...e,messages:i,outputMessage:s}}var
|
|
48
|
+
`);return{...e,messages:i,outputMessage:s}}var fa=new A(Ze);async function ya(e,r){let{messages:t}=await fa.invoke({messages:v(e.messages)},r),a=[],o=[];for(let s of t){let l=s.content,c;if(typeof l!="string"){c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:l}};continue}try{c=JSON.parse(l)}catch{c={tool:s.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:l}}}a.push(c),c.details&&typeof c.details=="object"&&"error"in c.details?o.push(`- ${c.tool}: Error - ${String(c.details.error)}`):o.push(`- ${c.layerName}: ${c.summary}`)}let i=[...e.messages,...t];return await h({text:`Finished executing layer query tool: ${o.join(", ")}`},r),{...e,messages:i,queryResponse:a}}var ga=10,pa=async(e,r)=>{let t=null,a=null;try{r.type!=="geometry"&&r.type!=="oid"&&r.type!=="global-id"&&(t=await fe({layer:e,field:r.name}),r.type==="string"&&(a=(await ye({layer:e,field:r.name})).uniqueValueInfos.sort((o,i)=>i.count-o.count).slice(0,ga)))}catch(o){console.error(`Error fetching statistics for field ${r.name}:`,o)}return{summaryStatistics:t,uniqueValues:a}};async function Se(e,r,t){let a=[],o=[];for(let i of e){let s=function(f){let y=r.get(f)?.layerItem;return y?[y.name&&`Name: ${y.name}`,y.title&&`Title: ${y.title}`,y.description&&`Description: ${y.description}`].filter(Boolean).join(" | "):f},{layerId:l,results:c}=i,d=t.map?.allLayers.find(f=>f.id===l),u=r.get(l)?.fieldRegistry;if(!u)continue;let m=a.find(f=>f.layerId===l);m||(m={layerId:l,layerSummary:s(l),fieldInfos:[]},a.push(m));for(let f of c){let y=u.get(f.name);if(y){if(!y.statistics){let w=pa(d,y).then(S=>{u.set(y.name,{...y,statistics:S}),y.statistics=S});o.push(w)}m.fieldInfos.push(y)}}}return await Promise.all(o),a}var wa=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=b(r,"layersAndFieldsRegistry"),{mapView:a}=R(r),o=await Se(e.vectorSearchFieldResults,t,a);return console.log("Field statistics retrieved:",o),await h({text:"Statistics retrieved"},r),{...e,layerFieldInfo:o}}catch(t){throw await h({text:"Error during fetching statistics"},r),new Error(`Error during fetching statistics: ${t instanceof Error?t.message:String(t)}`)}},je=.7,ba=10,va=async(e,r)=>{try{let t=_(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:je,topResults:ba,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
|
|
50
49
|
`);return`${o.get(d)?.layerItem.name??d}:
|
|
51
50
|
${m}`}).join(`
|
|
52
51
|
`),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
|
|
53
|
-
${l}`:c=`No vector search results found for score over ${
|
|
52
|
+
${l}`:c=`No vector search results found for score over ${je}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},Sa=.7,Ta=async(e,r)=>{try{let t=_(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchLayers({text:t,minScore:Sa,embeddingCache:i}),l=s.map(u=>u.id),c=s.map(({id:u,score:m})=>`${o.get(u)?.layerItem.name??u} (${m.toFixed(2)})`).join(`
|
|
54
53
|
`),d;return l.length>0?d=`Vector search completed. Matching layers with scores:
|
|
55
|
-
${c}`:d="Vector search completed. No matching layers found.",await h({text:d},r),{...e,vectorSearchLayerIds:l}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},
|
|
54
|
+
${c}`:d="Vector search completed. No matching layers found.",await h({text:d},r),{...e,vectorSearchLayerIds:l}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},xa=(e,r)=>B(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,r),Ea=()=>new q(He).addNode("requireDataExplorationServices",xa).addNode("vectorSearchLayers",Ta).addNode("vectorSearchFields",va).addNode("fieldStatistics",wa).addNode("queryAgent",ua).addNode("queryTools",ya).addNode("summarizeQueryResponseLLM",ha).addNode("filterAgent",da).addNode("filterTools",ma).addNode("earlyExit",kr).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.messages[e.messages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addEdge("filterAgent","filterTools").addEdge("filterTools",x).addEdge("summarizeQueryResponseLLM",x).addEdge("earlyExit",x),Ia=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).
|
|
56
55
|
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.
|
|
57
56
|
_Example: “Only show stations where Brand is Shell”_
|
|
58
57
|
_Example: “Make Shell stations stand out on the map”_
|
|
@@ -60,47 +59,47 @@ ${c}`:d="Vector search completed. No matching layers found.",await h({text:d},r)
|
|
|
60
59
|
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?”).
|
|
61
60
|
_Example: “How many features are there?”_
|
|
62
61
|
_Example: “What’s the average population?”_
|
|
63
|
-
_Example: “Which values are in the status field?”_`,
|
|
62
|
+
_Example: “Which values are in the status field?”_`,ml={id:"dataExploration",name:"Data Exploration Agent",description:Ia,createGraph:Ea,workspace:He},Ve=.7,La=10,$a=async(e,r)=>{try{let t=_(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Ve,topResults:La,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
|
|
64
63
|
`);return`${o.get(d)?.layerItem.name??d}:
|
|
65
64
|
${m}`}).join(`
|
|
66
65
|
`),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
|
|
67
|
-
${l}`:c=`No vector search results found for score over ${
|
|
66
|
+
${l}`:c=`No vector search results found for score over ${Ve}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},Fa=.7,_a=async(e,r)=>{try{let t=_(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:Fa}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
|
|
68
67
|
`),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
|
|
69
|
-
${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},
|
|
68
|
+
${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},Xe=["mapView"];function ee(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerFilterAgent context missing");let t=Xe.filter(a=>!(a in r));if(t.length)throw new Error(`LayerFilterAgent context missing: ${t.join(", ")}`);return r}var ka=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=b(r,"layersAndFieldsRegistry"),{mapView:a}=ee(r),o=await Se(e.vectorSearchFieldResults,t,a);return console.log("Field statistics retrieved:",o),await h({text:"Statistics retrieved"},r),{...e,layerFieldInfo:o}}catch(t){throw await h({text:"Error during fetching statistics"},r),new Error(`Error during fetching statistics: ${t instanceof Error?t.message:String(t)}`)}},Te=async(e,r,t)=>{let a=e.map?.allLayers.find(s=>s.id===r),o=a.createQuery();o.where=t??"1=1";let{features:i}=await a.queryFeatures(o);e.goTo(i)},Na=(e,r,t)=>{let a=t.map?.allLayers.find(o=>o.id===e);return a?(a.definitionExpression=r,a.visible=!0,Te(t,e,r),`Applied definition expression to layer "${a.title??e}": ${r}`):`Could not find layer with ID: ${e}`},qa=({layerId:e,definitionExpression:r},t)=>{let{mapView:a}=ee(t);return Na(e,r,a)},Aa=n.object({layerId:n.string().describe("The layerId of the layer on which to set a definitionExpression."),definitionExpression:n.string().describe("The SQL-92 where clause used to set a definition expression on the layer.")}),Ra=p(qa,{name:"setDefinitionExpression",description:"Set a SQL-92 where clause to the definition expression of a layer (i.e. a server-side filter). This filters features at the server level, affecting all views of the layer. Do not prioritize this tool unless specifically asked for or implied for server level, affecting all views of the layer.",schema:Aa}),et=async(e,r)=>{let t=r.map?.allLayers.find(i=>i.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=await t.queryFeatures({where:e.where,returnGeometry:!0});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=Y.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},Ma=async(e,r,t,a,o)=>{let i=r.map?.allLayers.find(l=>l.id===e.layerId);if(!i)return`Could not find target layer with ID: ${e.layerId}`;console.log("Layer type:",i.type),console.log("Layer geometryType:",i.geometryType),console.log("Layer renderer:",i.renderer?.type);let s;if(o){let l=await et(o,r);if("error"in l)return l.error;s=l.geometry}return i.featureEffect=new Be({filter:new V({where:e.where,geometry:s,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:t,excludedEffect:a}),i.visible=!0,Te(r,o?o.layerId:e.layerId,o?o.where:e.where),`Applied feature effects to target layer "${i.title??e.layerId}"${o?` using geometry from layer "${o.layerId}"`:""}.`},za=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],tt=n.enum(za),Ca=async({targetLayer:e,geometryLayer:r,includedEffect:t="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:a="grayscale(100%) opacity(60%) blur(2px)"},o)=>{let{mapView:i}=ee(o);return await Ma(e,i,t,a,r)},ja=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a feature effect."),where:n.string().describe("The SQL-92 where clause representing the features to emphasize.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:tt.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),includedEffect:n.string().optional().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:n.string().optional().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.")}),Va=p(Ca,{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:ja}),Oa=async(e,r,t)=>{let a=r.map?.allLayers.find(s=>s.id===e.layerId);if(!a)return`Could not find target layer with ID: ${e.layerId}`;let o;if(t){let s=await et(t,r);if("error"in s)return s.error;o=s.geometry}let i=await r.whenLayerView(a);return i.filter=new V({where:e.where,geometry:o,spatialRelationship:"intersects",distance:t?.distance,units:t?.units}),a.visible=!0,Te(r,t?t.layerId:e.layerId,t?t.where:e.where),`Applied feature filter to layer "${a.title??e.layerId}"${t?` using geometry from layer "${t.layerId}"`:""}.`},Da=async({targetLayer:e,geometryLayer:r},t)=>{let{mapView:a}=ee(t);return await Oa(e,a,r)},Pa=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer on which to set a filter."),where:n.string().describe("The SQL-92 where clause representing the features to display.")}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to filter the input geometry."),units:tt.describe("The units used to filter by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),Ga=p(Da,{name:"setFeatureFilter",description:"Sets a client-side filter using a where clause, geometry filter, or both on a target layer. This filters features at the client level in the view.",schema:Pa}),rt=[Ra,Va,Ga],Ba=async(e,r)=>{await h({text:"Requesting LLM for layer filter results"},r);let t=await F("layer_filter_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:v(e.messages),inputVariables:i,tools:rt}),l=s.content.toString();return await Q(s,r),{...e,messages:[...e.messages,s],outputMessage:l}};async function Qa(e,r){let t=await new A(rt).invoke({messages:v(e.messages)},r),a=t.messages.map(s=>s.text).join(`
|
|
70
69
|
`);await h({text:`Finished executing layer filter tool: ${a}`},r);let o=[...e.messages,...t.messages],i=t.messages.map(s=>s.text).join(`
|
|
71
|
-
`);return{...e,outputMessage:i,messages:o}}var
|
|
70
|
+
`);return{...e,outputMessage:i,messages:o}}var at=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
72
71
|
|
|
73
72
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
74
73
|
|
|
75
|
-
${t}`},default:()=>""}),vectorSearchLayerIds:
|
|
74
|
+
${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g()}),Wa=async(e,r)=>(await h({text:"Exiting Layer Filter agent"},r),e),Ka=(e,r)=>B(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Filter Agent")(e,r),Ua=()=>new q(at).addNode("requireLayerFilterServices",Ka).addNode("vectorSearchLayers",_a).addNode("vectorSearchFields",$a).addNode("fieldStatistics",ka).addNode("agent",Ba).addNode("tools",Qa).addNode("earlyExit",Wa).addEdge(N,"requireLayerFilterServices").addEdge("requireLayerFilterServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","agent").addConditionalEdges("agent",e=>(e.messages[e.messages.length-1]?.tool_calls?.length??0)>0?"tools":"earlyExit").addEdge("tools","earlyExit").addEdge("earlyExit",x),Ja=String.raw`- **layer filter** — User wants to include or exclude features based on field values, or visually style features differently (e.g., highlight or deemphasize them).
|
|
76
75
|
The Layer Filter Agent will automatically zoom to the affected features for action taken by this agent. In this case, no need to call navigation tool separately.
|
|
77
76
|
_Example: “Only show stations where Brand is Shell”_
|
|
78
77
|
_Example: “Make Shell stations stand out on the map”_
|
|
79
|
-
_Example: “Gray out all stations that aren’t Shell”_`,
|
|
78
|
+
_Example: “Gray out all stations that aren’t Shell”_`,fl={id:"layerFilter",name:"Layer Filter Agent",description:Ja,createGraph:Ua,workspace:at},ot=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
80
79
|
|
|
81
80
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
82
81
|
|
|
83
|
-
${t}`},default:()=>""}),vectorSearchLayerIds:
|
|
82
|
+
${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponses:g()}),Ha=async(e,r)=>(await h({text:"Exiting Layer Query agent"},r),e);function K(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerQueryAgent context missing");let t=Xe.filter(a=>!(a in r));if(t.length)throw new Error(`LayerQueryAgent context missing: ${t.join(", ")}`);return r}var Za=async(e,r)=>{try{await h({text:"Getting statistics for vector search results"},r);let t=b(r,"layersAndFieldsRegistry"),{mapView:a}=K(r),o=await Se(e.vectorSearchFieldResults,t,a);return console.log("Field statistics retrieved:",o),await h({text:"Statistics retrieved"},r),{...e,layerFieldInfo:o}}catch(t){throw await h({text:"Error during fetching statistics"},r),new Error(`Error during fetching statistics: ${t instanceof Error?t.message:String(t)}`)}},Oe=.7,Ya=10,Xa=async(e,r)=>{try{let t=_(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:Oe,topResults:Ya,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
|
|
84
83
|
`);return`${o.get(d)?.layerItem.name??d}:
|
|
85
84
|
${m}`}).join(`
|
|
86
85
|
`),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
|
|
87
|
-
${l}`:c=`No vector search results found for score over ${
|
|
86
|
+
${l}`:c=`No vector search results found for score over ${Oe}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},eo=.7,to=async(e,r)=>{try{let t=_(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:eo}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
|
|
88
87
|
`),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
|
|
89
|
-
${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},lo=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},co=async(e,r,t,a)=>{let o=a.map?.allLayers.find(c=>c.id===e),i=lo(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${l}`,details:{fieldName:r,value:l,where:t.where}}};async function uo({layerId:e,fieldName:r,query:t},a){let{mapView:o}=K(a),i=await co(e,r,t,o);return JSON.stringify(i,null,2)}var ho=n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:n.string().describe("The name of the field/attribute from which to get a field value."),query:n.object({where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),mo=p(uo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:ho}),Ee=async(e,r)=>{let t=r.map?.allLayers.find(i=>i.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=await t.queryFeatures({where:e.where,returnGeometry:!0});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=Y.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},fo=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryLayer:s}=e,l=o.map?.allLayers.find(g=>g.id===r.layerId);if(!l)throw new Error(`Layer '${r.layerId}' not found.`);let c=i.get(r.layerId)?.fieldRegistry.get(t);if(!c)throw new Error(`Field '${t}' not found.`);let d;if(s){let g=await Ee(s,o);if("error"in g)throw new Error(g.error);if(d=g.geometry,s.distance&&s.units){let b=Ue.execute(d,s.distance,{unit:s.units==="us-nautical-miles"?"nautical-miles":s.units});b&&(d=b)}}else d=o.extent.clone();let u=new V({geometry:d,spatialRelationship:"intersects"}),m=null,f=null;try{m=await ge({layer:l,field:t,sqlWhere:r.where,filter:u,outStatisticTypes:{include:[a]}}),c.type==="string"&&(f=(await ye({layer:l,field:t,sqlWhere:r.where,filter:u})).uniqueValueInfos)}catch(g){console.error("Statistics error:",g)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof m?.[a]=="number"?m[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:m?.[a]??null,summaryStatistics:m,uniqueValues:f,where:r.where}}},go=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],yo=n.enum(go);async function po({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=w(o,"layersAndFieldsRegistry"),{mapView:s}=K(o),l=await fo({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return console.log(l),JSON.stringify(l,null,2)}var wo=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryLayer:n.union([n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:yo.optional().describe("The units used to query by geometry and distance.")}),n.object({}).strict()]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),fieldName:n.string().describe("The name of the field for which to get statistics."),statisticType:n.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),bo=p(po,{name:"getStatistics",description:"Returns one or more summary statistics for the given field. Statistic types include: count, maximum, minimum, average, median, standard deviation, variance, mode, sum, nullcount (number of features without a value for a given field), unique values. Statistics can be returned for number, date, and string fields. Only call this tool when the question requires filtering (e.g. a WHERE clause or spatial constraint) that cannot be satisfied by precomputed stats.",schema:wo}),vo=async(e,r,t,a)=>{let o=t.map?.allLayers.find(d=>d.id===e.layerId),i=a?await Ee(a,t):{geometry:void 0},s="geometry"in i?i.geometry:void 0,l=new We({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,geometry:s,spatialRelationship:s?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new Ke({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})}),c=await o.queryTopFeatures(l);return{tool:"getTopFeatures",layerName:o.title??e.layerId,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,features:c.features,where:e.where}}},So=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=K(a),i=await vo(e,r,o,t);return JSON.stringify(i,null,2)},To=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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."))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to query from the input geometry."),units:M.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),topFilter:n.object({topCount:n.number().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),groupByFields:n.array(n.string().describe("The field(s) for which to group by the top features."))})}),xo=p(So,{name:"getTopFeatures",description:"Returns the top n features from a layer",schema:To}),Eo=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId),o=t?await Ee(t,r):{geometry:void 0},i="geometry"in o?o.geometry:void 0,s=new pe({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,geometry:i,spatialRelationship:i?"intersects":void 0,distance:t?.distance,units:t?.units}),l=await a.queryFeatures(s);return{tool:"queryFeatures",layerName:a.title??e.layerId,summary:`${l.features.length} features found`,details:{totalCount:l.features.length,features:l.features.slice(0,10),where:e.where}}};async function Io({targetLayer:e,geometryLayer:r},t){let{mapView:a}=K(t),o=await Eo(e,a,r);return JSON.stringify(o,null,2)}var Lo=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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."))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to query from the input geometry."),units:M.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),$o=p(Io,{name:"queryFeatures",description:"Queries for one or more features from a given layer.",schema:Lo}),nt=[$o,bo,mo,xo],Fo=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("data_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:S(e.messages),inputVariables:i,tools:nt});if(!(s.tool_calls&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0))return{...e,messages:[...e.messages,s]};let l=s.content.toString()||"LLM requested tool calls.";return await Q(s,r),{...e,outputMessage:l,messages:[...e.messages,s]}},_o=new A(nt);async function No(e,r){let{messages:t}=await _o.invoke({messages:S(e.messages)},r),a=[],o=[];for(let l of t){let c=l.content;if(typeof c!="string"){console.warn("Skipping non-string tool output:",c);continue}let d;try{d=JSON.parse(c)}catch{console.warn("Skipping invalid JSON from tool:",c);continue}a.push(d),o.push(`- ${d.layerName}: ${d.summary}`)}if(o.length===0)return{...e,queryResponses:a};let i=new j({content:`Query results:
|
|
88
|
+
${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},ro=(e,r,t)=>{let a=e.createQuery();return a.outFields=[r],a.where=t||"1=1",a.num=1,a},ao=async(e,r,t,a)=>{let o=a.map?.allLayers.find(c=>c.id===e),i=ro(o,r,t.where),s=(await o.queryFeatures(i)).features[0],l=s?s.attributes[r]:null;return{tool:"getAttribute",layerName:o.title??e,summary:`${r} = ${l}`,details:{fieldName:r,value:l,where:t.where}}};async function oo({layerId:e,fieldName:r,query:t},a){let{mapView:o}=K(a),i=await ao(e,r,t,o);return JSON.stringify(i,null,2)}var io=n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:n.string().describe("The name of the field/attribute from which to get a field value."),query:n.object({where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),no=p(oo,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:io}),xe=async(e,r)=>{let t=r.map?.allLayers.find(i=>i.id===e.layerId);if(!t)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=await t.queryFeatures({where:e.where,returnGeometry:!0});if(!a.features.length)return{error:`No features found in geometry layer with the specified where clause: ${e.where}`};let o;if(a.features.length===1){let i=a.features[0].geometry;if(!i)return{error:"The geometry of the first feature is undefined or null."};o=i}else{let i=a.features.map(l=>l.geometry),s=Y.executeMany(i);if(!s)return{error:"Failed to create a combined geometry."};o=s}return{geometry:o}},so=async e=>{let{targetLayer:r,fieldName:t,statisticType:a,mapView:o,layersAndFieldsRegistry:i,geometryLayer:s}=e,l=o.map?.allLayers.find(y=>y.id===r.layerId);if(!l)throw new Error(`Layer '${r.layerId}' not found.`);let c=i.get(r.layerId)?.fieldRegistry.get(t);if(!c)throw new Error(`Field '${t}' not found.`);let d;if(s){let y=await xe(s,o);if("error"in y)throw new Error(y.error);if(d=y.geometry,s.distance&&s.units){let w=Ke.execute(d,s.distance,{unit:s.units==="us-nautical-miles"?"nautical-miles":s.units});w&&(d=w)}}else d=o.extent.clone();let u=new V({geometry:d,spatialRelationship:"intersects"}),m=null,f=null;try{m=await fe({layer:l,field:t,sqlWhere:r.where,filter:u,outStatisticTypes:{include:[a]}}),c.type==="string"&&(f=(await ye({layer:l,field:t,sqlWhere:r.where,filter:u})).uniqueValueInfos)}catch(y){console.error("Statistics error:",y)}return{tool:"getStatistics",layerName:l.title??r.layerId,summary:`${a} = ${typeof m?.[a]=="number"?m[a]:"N/A"}`,details:{fieldName:t,statisticType:a,statistic:m?.[a]??null,summaryStatistics:m,uniqueValues:f,where:r.where}}},lo=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],co=n.enum(lo);async function uo({targetLayer:e,fieldName:r,statisticType:t,geometryLayer:a},o){let i=b(o,"layersAndFieldsRegistry"),{mapView:s}=K(o),l=await so({targetLayer:e,fieldName:r,statisticType:t,mapView:s,layersAndFieldsRegistry:i,geometryLayer:a});return console.log(l),JSON.stringify(l,null,2)}var ho=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryLayer:n.union([n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().optional().describe("The distance by which to query from the input geometry."),units:co.optional().describe("The units used to query by geometry and distance.")}),n.object({}).strict()]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),fieldName:n.string().describe("The name of the field for which to get statistics."),statisticType:n.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),mo=p(uo,{name:"getStatistics",description:"Returns one or more summary statistics for the given field. Statistic types include: count, maximum, minimum, average, median, standard deviation, variance, mode, sum, nullcount (number of features without a value for a given field), unique values. Statistics can be returned for number, date, and string fields. Only call this tool when the question requires filtering (e.g. a WHERE clause or spatial constraint) that cannot be satisfied by precomputed stats.",schema:ho}),fo=async(e,r,t,a)=>{let o=t.map?.allLayers.find(d=>d.id===e.layerId),i=a?await xe(a,t):{geometry:void 0},s="geometry"in i?i.geometry:void 0,l=new Qe({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,geometry:s,spatialRelationship:s?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new We({topCount:r.topCount,groupByFields:r.groupByFields,orderByFields:r.orderByFields})}),c=await o.queryTopFeatures(l);return{tool:"getTopFeatures",layerName:o.title??e.layerId,summary:`Top ${r.topCount} features extracted`,details:{topCount:r.topCount,features:c.features,where:e.where}}},yo=async({targetLayer:e,topFilter:r,geometryLayer:t},a)=>{let{mapView:o}=K(a),i=await fo(e,r,o,t);return JSON.stringify(i,null,2)},go=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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."))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to query from the input geometry."),units:M.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries."),topFilter:n.object({topCount:n.number().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),groupByFields:n.array(n.string().describe("The field(s) for which to group by the top features."))})}),po=p(yo,{name:"getTopFeatures",description:"Returns the top n features from a layer",schema:go}),wo=async(e,r,t)=>{let a=r.map?.allLayers.find(c=>c.id===e.layerId),o=t?await xe(t,r):{geometry:void 0},i="geometry"in o?o.geometry:void 0,s=new ge({where:e.where||"1=1",outFields:e.outFields.length?e.outFields:["*"],orderByFields:e.orderByFields,geometry:i,spatialRelationship:i?"intersects":void 0,distance:t?.distance,units:t?.units}),l=await a.queryFeatures(s);return{tool:"queryFeatures",layerName:a.title??e.layerId,summary:`${l.features.length} features found`,details:{totalCount:l.features.length,features:l.features.slice(0,10),where:e.where}}};async function bo({targetLayer:e,geometryLayer:r},t){let{mapView:a}=K(t),o=await wo(e,a,r);return JSON.stringify(o,null,2)}var vo=n.object({targetLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the field from which to get a value."),where:n.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:n.array(n.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:n.array(n.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."))}),geometryLayer:n.object({layerId:n.string().describe("The layerId of the layer containing the geometry by which to filter."),where:n.string().describe("The SQL-92 where clause representing the features from which to filter features from the targetLayer by geometry."),distance:n.number().describe("The distance by which to query from the input geometry."),units:M.describe("The units used to query by geometry and distance.")}).optional().describe("Optional geometry-based filtering parameters for spatial queries.")}),So=p(bo,{name:"queryFeatures",description:"Queries for one or more features from a given layer.",schema:vo}),it=[So,mo,no,po],To=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("data_query_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=X(),i={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o},s=await C({promptText:t,messages:v(e.messages),inputVariables:i,tools:it});if(!(s.tool_calls&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0))return{...e,messages:[...e.messages,s]};let l=s.content.toString()||"LLM requested tool calls.";return await Q(s,r),{...e,outputMessage:l,messages:[...e.messages,s]}},xo=new A(it);async function Eo(e,r){let{messages:t}=await xo.invoke({messages:v(e.messages)},r),a=[],o=[];for(let l of t){let c=l.content;if(typeof c!="string"){console.warn("Skipping non-string tool output:",c);continue}let d;try{d=JSON.parse(c)}catch{console.warn("Skipping invalid JSON from tool:",c);continue}a.push(d),o.push(`- ${d.layerName}: ${d.summary}`)}if(o.length===0)return{...e,queryResponses:a};let i=new j({content:`Query results:
|
|
90
89
|
${o.join(`
|
|
91
90
|
`)}`}),s=`Query results:
|
|
92
91
|
${o.join(`
|
|
93
|
-
`)}`;return{...e,outputMessage:s,messages:[...e.messages,...t,i],queryResponses:a}}var
|
|
92
|
+
`)}`;return{...e,outputMessage:s,messages:[...e.messages,...t,i],queryResponses:a}}var Io=async(e,r)=>{try{await h({text:"Requesting LLM for summary on query results"},r);let t=await F("summarize_query_response_prompt"),a={queryResponse:e.queryResponses},o=await oe({promptText:t,messages:v(e.messages),inputVariables:a}),i=typeof o=="string"?o:o.content;return e.messages=[...e.messages,new j(i)],e.outputMessage=i,await h({text:`Received response from LLM: ${i}`},r),e}catch(t){throw await h({text:"Error during filter LLM request"},r),new Error(`Error during filter LLM request: ${t instanceof Error?t.message:String(t)}`)}},Lo=(e,r)=>B(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Query Agent")(e,r),$o=()=>new q(ot).addNode("requireLayerQueryServices",Lo).addNode("vectorSearchLayers",to).addNode("vectorSearchFields",Xa).addNode("fieldStatistics",Za).addNode("agent",To).addNode("tools",Eo).addNode("summarizeQueryResponseLLM",Io).addNode("earlyExit",Ha).addEdge(N,"requireLayerQueryServices").addEdge("requireLayerQueryServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","agent").addEdge("agent","tools").addConditionalEdges("tools",e=>e.queryResponses.length?"summarizeQueryResponseLLM":"earlyExit").addEdge("summarizeQueryResponseLLM",x).addEdge("earlyExit",x),Fo=String.raw`- **layerQuery** — 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. CRITICAL: Always call the Layer Filter Agent after this agent.
|
|
94
93
|
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?”).
|
|
95
94
|
_Example: “How many features are there?”_
|
|
96
95
|
_Example: “What’s the average population?”_
|
|
97
|
-
_Example: “Which values are in the status field?”_`,
|
|
96
|
+
_Example: “Which values are in the status field?”_`,yl={id:"layerQuery",name:"Layer Query Agent",description:Fo,createGraph:$o,workspace:ot},De=.7,_o=10,ko=async(e,r)=>{try{let t=_(e.messages);await h({text:"Similarity search to find fields"},r);let a=b(r,"fieldSearch"),o=b(r,"layersAndFieldsRegistry"),i=b(r,"embeddingCache"),s=await a.searchFields({text:t,layerIds:e.vectorSearchLayerIds,minScore:De,topResults:_o,embeddingCache:i}),l=s.map(({layerId:d,results:u})=>{let m=u.map(f=>` - ${f.name} (${f.score.toFixed(2)})`).join(`
|
|
98
97
|
`);return`${o.get(d)?.layerItem.name??d}:
|
|
99
98
|
${m}`}).join(`
|
|
100
99
|
`),c;return s.length>0?c=`Vector search completed. Matching layers and fields with scores:
|
|
101
|
-
${l}`:c=`No vector search results found for score over ${
|
|
100
|
+
${l}`:c=`No vector search results found for score over ${De}.`,await h({text:c},r),{...e,vectorSearchFieldResults:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}},No=.7,qo=async(e,r)=>{try{let t=_(e.messages);await h({text:`Similarity search to find layers: ${t}`},r);let a=b(r,"layerSearch"),o=b(r,"layersAndFieldsRegistry"),i=await a.searchLayers({text:t,minScore:No}),s=i.map(d=>d.id),l=i.map(({id:d,score:u})=>`${o.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
|
|
102
101
|
`),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
|
|
103
|
-
${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}};async function
|
|
102
|
+
${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r),{...e,vectorSearchLayerIds:s}}catch(t){throw await h({text:`Error during vector search: ${t instanceof Error?t.message:String(t)}`},r),new Error(`Vector search failed: ${t instanceof Error?t.message:String(t)}`)}};async function Ao(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i?s=pt({basemapTheme:await Ae(a),geometryType:t.geometryType,includedTags:i,numColors:Math.min(r.length,8)})[0]:s=wt({basemapTheme:await Ae(a),geometryType:t.geometryType,numColors:Math.min(r.length,8)}).primaryScheme,{layer:t,view:a,attributes:r.map(l=>({field:l,label:t.fields.find(c=>c.name===l)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function Ro(e){return await gt(e)}async function Mo({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,includeSize:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:i?"chart-size":"chart",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=await Ao(c),u=await Ro(d);return l.renderer=u.renderer,l.visible=!0,`Chart renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying chart renderer: ${d instanceof Error?d.message:String(d)}`}}var zo=["mapView"];function I(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("LayerStylingAgent context missing");let t=zo.filter(a=>!(a in r));if(t.length)throw new Error(`LayerStylingAgent context missing: ${t.join(", ")}`);return r}async function Co({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Mo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var jo=n.object({layerId:n.string().describe("The id of the layer to apply the chart renderer to"),fields:n.array(n.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),includeSize:n.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),Vo=p(Co,{name:"chart",description:`Label: Charts
|
|
104
103
|
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
105
104
|
Keywords: pie, chart, all categories, breakdown, proportion
|
|
106
105
|
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
@@ -110,19 +109,19 @@ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r)
|
|
|
110
109
|
Description: Show the values of two or more categories as a proportion of the total using a pie chart and use size to capture the total amount or magnitude.
|
|
111
110
|
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
112
111
|
Example: Show the total number of homes built in each decade using a pie chart for each feature and vary the size of each chart based on the total of all categories.
|
|
113
|
-
Fields: This style requires 2-8 number fields.`,schema:
|
|
112
|
+
Fields: This style requires 2-8 number fields.`,schema:jo});function Oo(e){let{fields:r,layer:t,view:a,theme:o,colorSchemeTags:i}=e,s=r[0],l;return i&&(l=pe({geometryType:t.geometryType,includedTags:i,theme:o||"high-to-low"})[0]),{layer:t,view:a,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:l}}async function Do(e){return await bt(e)}async function Po({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"color-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Oo(c),u=await Do(d);return l.renderer=u.renderer,l.visible=!0,`Color-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Go({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Po({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Bo=n.object({layerId:n.string().describe("The id of the layer to apply the color-age renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Qo=p(Go,{name:"color-age",description:`Label: Age (color)
|
|
114
113
|
Description: Use colors along a continuous color ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
115
114
|
Keywords: since, age, how old, how long
|
|
116
115
|
Example: Show the age of each feature based on its reported date.
|
|
117
|
-
Fields: This style requires at least one field with a date type.`,schema:
|
|
116
|
+
Fields: This style requires at least one field with a date type.`,schema:Bo});function Wo(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,{theme:i}=e,s=r[1],l=r[0],c;return o&&(c=pe({geometryType:t.geometryType,includedTags:o,theme:i||"high-to-low"})[0]),{layer:t,view:a,field:l,normalizationField:s,theme:i,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function Ko(e){return await vt(e)}async function Uo({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"color",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Wo(c),u=await Ko(d);return l.renderer=u.renderer,l.visible=!0,`Color renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color renderer: ${d instanceof Error?d.message:String(d)}`}}async function Jo({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Uo({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Ho=n.object({layerId:n.string().describe("The id of the layer to apply the color renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the color renderer"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),Zo=p(Jo,{name:"color",description:`Label: Counts and Amounts (color)
|
|
118
117
|
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
119
118
|
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
120
119
|
Example: Color each feature based on the population density.
|
|
121
|
-
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:
|
|
120
|
+
Fields: This style requires a single field with a number type. A second number field may be specified for normalizing the value of the first field.`,schema:Ho});function Yo(e){let{fields:r,layer:t,view:a,colorSchemeTags:o,theme:i}=e,s,l,c=r[0];return o&&(l=pe({geometryType:t.geometryType,includedTags:o,theme:i||"high-to-low"})[0]),{layer:t,view:a,field:c,normalizationField:s,theme:i,colorOptions:{colorScheme:l}}}async function Xo(e){return await St(e)}async function ei({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"color-size-univariate",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Yo(c),u=await Xo(d);return l.renderer=u.renderer,l.visible=!0,`Color-size-univariate renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-size-univariate renderer: ${d instanceof Error?d.message:String(d)}`}}async function ti({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await ei({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ri=n.object({layerId:n.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:n.array(n.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),ai=p(ti,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
122
121
|
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
123
122
|
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
124
123
|
Example: Color each feature based on the percentage of the population that owns a home and vary the size of each point based on total population.
|
|
125
|
-
Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:
|
|
124
|
+
Fields: This style requires at least two fields: one determining the color of each feature, the other determining the size of each feature. Each field may be normalized by an additional normalization field.`,schema:ri});function oi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i;return o&&(i=xt({includedTags:o,numColors:Math.min(r.length,8)})[0]),{layer:t,view:a,legendOptions:{unit:"units"},attributes:r.map(s=>({field:s,label:t.fields.find(l=>l.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:i}}async function ii(e){return await Tt(e)}async function ni({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o}){let i=r,s=e?.allLayers.find(c=>c.id===t);if(!s)return`Could not find layer for id: ${t}`;let l={styleName:"dot-density",fields:a,layer:s,view:i,colorSchemeTags:o};try{let c=oi(l),d=await ii(c);return s.renderer=d.renderer,s.visible=!0,`Dot Density renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying dot density renderer: ${c instanceof Error?c.message:String(c)}`}}async function si({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=I(a);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await ni({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var li=n.object({layerId:n.string().describe("The id of the layer to apply the dot density renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use")}),ci=p(si,{name:"dot-density",description:`Dot Density
|
|
126
125
|
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
127
126
|
**Use cases:**
|
|
128
127
|
- Population distribution visualization
|
|
@@ -133,11 +132,11 @@ ${l}`:c="Vector search completed. No matching layers found.",await h({text:c},r)
|
|
|
133
132
|
- Visualize distribution of different crops across regions
|
|
134
133
|
- Display demographic patterns within census tracts
|
|
135
134
|
**Fields:** Requires 2-8 number fields.
|
|
136
|
-
**Keywords:** density, how much, how many, total, number, amount`,schema:
|
|
135
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:li});function di(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s=r[0];return o&&(i=It({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:t,view:a,field:s,heatmapScheme:i}}async function ui(e){return await Et(e)}async function hi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o}){let i=r,s=e?.allLayers.find(c=>c.id===t);if(!s)return`Could not find layer for id: ${t}`;let l={styleName:"heatmap",fields:a,layer:s,view:i,colorSchemeTags:o};try{let c=di(l),d=await ui(c);return s.renderer=d.renderer,s.visible=!0,`Heatmap renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying heatmap renderer: ${c instanceof Error?c.message:String(c)}`}}async function mi({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=I(a);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await hi({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var fi=n.object({layerId:n.string().describe("The id of the layer to apply the heatmap renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use")}),yi=p(mi,{name:"heatmap",description:`Label: Heat Map
|
|
137
136
|
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
138
137
|
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
139
138
|
Example: Create a heatmap
|
|
140
|
-
Fields: This typically requires zero or one field of type number.`,schema:
|
|
139
|
+
Fields: This typically requires zero or one field of type number.`,schema:fi});function gi(e){let{fields:r,layer:t,view:a,styleName:o,colorSchemeTags:i}=e,s;return i&&(s=$t({geometryType:t.geometryType,includedTags:i,numColors:Math.min(r.length,10)})[0]),{layer:t,view:a,fields:r.map(l=>({name:l})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function pi(e){return await Lt(e)}async function wi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,includeSize:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:i?"predominance-size":"predominance",fields:a,layer:l,view:s,colorSchemeTags:o};try{let d=gi(c),u=await pi(d);return l.renderer=u.renderer,l.visible=!0,`Predominance renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying predominance renderer: ${d instanceof Error?d.message:String(d)}`}}async function bi({layerId:e,fields:r,colorSchemes:t,includeSize:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await wi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,includeSize:a})}var vi=n.object({layerId:n.string().describe("The id of the layer to apply the predominance renderer to"),fields:n.array(n.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),includeSize:n.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),Si=p(bi,{name:"predominance",description:`Label: Predominant category
|
|
141
140
|
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
142
141
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
143
142
|
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
@@ -147,15 +146,15 @@ Fields: This typically requires zero or one field of type number.`,schema:vi});f
|
|
|
147
146
|
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value. Also varies the size of each symbol based on the total of all categories.
|
|
148
147
|
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
149
148
|
Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
|
|
150
|
-
Fields: This style relies on 2-10 number fields.`,schema:
|
|
149
|
+
Fields: This style relies on 2-10 number fields.`,schema:vi});function Ti(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e,i,s={field:r[0]},l={field:r[1]};return o&&(i=_t({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field1:s,field2:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:i}}async function xi(e){return await Ft(e)}async function Ei({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o}){let i=r,s=e?.allLayers.find(c=>c.id===t);if(!s)return`Could not find layer for id: ${t}`;let l={styleName:"relationship",fields:a,layer:s,view:i,colorSchemeTags:o};try{let c=Ti(l),d=await xi(c);return s.renderer=d.renderer,s.visible=!0,`Relationship renderer applied to layer: ${s.title??s.id} using fields ${a.join(", ")}`}catch(c){return`Error applying relationship renderer: ${c instanceof Error?c.message:String(c)}`}}async function Ii({layerId:e,fields:r,colorSchemes:t},a){let{mapView:o}=I(a);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},a),await Ei({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:r,colorSchemes:t})}var Li=n.object({layerId:n.string().describe("The id of the layer to apply the relationship renderer to"),fields:n.array(n.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use")}),$i=p(Ii,{name:"relationship",description:`Label: Relationship
|
|
151
150
|
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
152
151
|
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
153
152
|
Example: Show the relationship between tree height and carbon storage
|
|
154
|
-
Fields: This style requires two number fields.`,schema:
|
|
153
|
+
Fields: This style requires two number fields.`,schema:Li});function Fi(e){let{fields:r,layer:t,view:a,theme:o}=e,i=r[0];return{layer:t,view:a,startTime:i,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function _i(e){return await kt(e)}async function ki({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"size-age",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Fi(c),u=await _i(d);return l.renderer=u.renderer,l.visible=!0,`Size-age renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ni({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await ki({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var qi=n.object({layerId:n.string().describe("The id of the layer to apply the size-age renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Ai=p(Ni,{name:"size-age",description:`Label: Age (size)
|
|
155
154
|
Description: Vary symbol sizes along a continuous ramp to represent the age of features. Age reflects the length of time from a start date to an end date.
|
|
156
155
|
Keywords: since, age, how old, how long
|
|
157
156
|
Example: Change the size of features so older features are larger than new features.
|
|
158
|
-
Fields: This style requires at least one field with a date type.`,schema:
|
|
157
|
+
Fields: This style requires at least one field with a date type.`,schema:qi});function Ri(e){let{fields:r,layer:t,view:a}=e,{theme:o}=e,i=r[1],s=r[0];return{layer:t,view:a,field:s,normalizationField:i,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Mi(e){return await Nt(e)}async function zi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"size",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Ri(c),u=await Mi(d);return l.renderer=u.renderer,l.visible=!0,`Size renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ci({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await zi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var ji=n.object({layerId:n.string().describe("The id of the layer to apply the size renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Vi=p(Ci,{name:"size",description:`Label: Counts and Amounts (size)
|
|
159
158
|
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
160
159
|
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
161
160
|
Example: Vary the size of each point based on the total population.
|
|
@@ -165,25 +164,25 @@ Fields: This typically requires zero or one field of type number.`,schema:vi});f
|
|
|
165
164
|
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
166
165
|
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
167
166
|
Example: Vary the size of each feature based on the date a ticket was completed.
|
|
168
|
-
Fields: This style requires a single field with a date type.`,schema:
|
|
167
|
+
Fields: This style requires a single field with a date type.`,schema:ji});function Oi(e){let{fields:r,layer:t,view:a,colorSchemeTags:o}=e;console.log("processTypeRendererParams",e);let i=r[0],s=r[1],l=r[2],c;return o&&(c=At({geometryType:t.geometryType,includedTags:o})[0]),{layer:t,view:a,field:i,field2:s,field3:l,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function Di(e){return await qt(e)}async function Pi({arcgisMap:e,arcgisMapView:r,layerId:t,fields:a,colorSchemes:o,theme:i}){let s=r,l=e?.allLayers.find(d=>d.id===t);if(!l)return`Could not find layer for id: ${t}`;let c={styleName:"type",fields:a,layer:l,view:s,colorSchemeTags:o,theme:i};try{let d=Oi(c),u=await Di(d);return l.renderer=u.renderer,l.visible=!0,`Type renderer applied to layer: ${l.title??l.id} using fields ${a.join(", ")}`}catch(d){return`Error applying type renderer: ${d instanceof Error?d.message:String(d)}`}}async function Gi({layerId:e,fields:r,colorSchemes:t,theme:a},o){let{mapView:i}=I(o);return await E({id:"show-legend",description:"Show Legend",payload:{layerIds:[e]}},o),await Pi({arcgisMap:i.map,arcgisMapView:i,layerId:e,fields:r,colorSchemes:t,theme:a})}var Bi=n.object({layerId:n.string().describe("The id of the layer to apply the type renderer to"),fields:n.array(n.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:n.array(n.string()).optional().describe("Optional color scheme tags to use"),theme:n.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),Qi=p(Gi,{name:"type",description:`Label: Types (unique symbols)
|
|
169
168
|
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
170
169
|
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
171
170
|
Example: Color each feature based on the region it belongs to
|
|
172
|
-
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:
|
|
171
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:Bi}),nt=[Vo,Qo,Zo,ai,ci,yi,Si,$i,Ai,Vi,Qi],Wi=async(e,r)=>{await h({text:"Requesting LLM for layer query results"},r);let t=await F("navigation_intent_prompt");if(!r?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await C({promptText:t,messages:v(e.messages),inputVariables:a,tools:nt});return await Q(o,r),{...e,messages:[...e.messages,o]}};async function Ki(e,r){let t=await new A(nt).invoke({messages:v(e.messages)},r),a=t.messages.map(i=>i.text).join(`
|
|
173
172
|
`);await h({text:`Finished executing layer filter tool: ${a}`},r);let o=t.messages.map(i=>i.text).join(`
|
|
174
|
-
`);return{...e,outputMessage:o}}var
|
|
173
|
+
`);return{...e,outputMessage:o}}var st=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
175
174
|
|
|
176
175
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
177
176
|
|
|
178
|
-
${t}`},default:()=>""}),vectorSearchLayerIds:
|
|
177
|
+
${t}`},default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),Ui=async(e,r)=>(await h({text:"Exiting Layer Styling agent"},r),e),Ji=async(e,r)=>{try{await h({text:"Populating layer and field info"},r);let t=[];for(let a of e.vectorSearchFieldResults){let o=function(u){let m=l.get(u)?.layerItem;return m?[m.name&&`Name: ${m.name}`,m.title&&`Title: ${m.title}`,m.description&&`Description: ${m.description}`].filter(Boolean).join(" | "):u},{layerId:i,results:s}=a,l=b(r,"layersAndFieldsRegistry"),c=l.get(i)?.fieldRegistry;if(!c)continue;let d=t.find(u=>u.layerId===i);d||(d={layerId:i,layerSummary:o(i),fieldInfos:[]},t.push(d));for(let u of s){let m=c.get(u.name);m&&d.fieldInfos.push(m)}}return console.log("Populated layerFieldInfo:",t),await h({text:"Populated layerFieldInfo"},r),{...e,layerFieldInfo:t}}catch(t){throw await h({text:"Error populating layerFieldInfo"},r),new Error(`Error populating layerFieldInfo: ${t instanceof Error?t.message:String(t)}`)}},Hi=(e,r)=>{let t=e.vectorSearchLayerIds??[];if(t.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=r.configurable;if(console.log("hitlResponse:",a),!a||a.agentId!==Pe.id||a.id!=="reviewLayerSelection"){let i={agentId:Pe.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...t]};throw new Le(i)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},Zi=(e,r)=>B(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,r),Yi=()=>new q(st).addNode("requireLayerStylingServices",Zi).addNode("vectorSearchLayers",qo).addNode("layerSelectionHITL",Hi).addNode("vectorSearchFields",ko).addNode("populateLayerFieldInfo",Ji).addNode("agent",Wi).addNode("tools",Ki).addNode("earlyExit",Ui).addEdge(N,"requireLayerStylingServices").addEdge("requireLayerStylingServices","vectorSearchLayers").addConditionalEdges("layerSelectionHITL",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"populateLayerFieldInfo":"earlyExit").addEdge("populateLayerFieldInfo","agent").addEdge("agent","tools").addEdge("tools",x).addEdge("earlyExit",x),Xi=String.raw`- **layerStyling** — User wants to change how features are drawn or styled on the map based on their data, such as applying color, size, transparency, symbols, or charts according to field values.
|
|
179
178
|
_Example: “Color points by sales amount”_
|
|
180
179
|
_Example: “Show population density with a color gradient”_
|
|
181
180
|
_Example: “Create a relationship map between height and depth”_
|
|
182
|
-
_Example: “Vary circle sizes according to population”_`,
|
|
181
|
+
_Example: “Vary circle sizes according to population”_`,Pe={id:"layerStyling",name:"Layer Styling Agent",description:Xi,createGraph:Yi,workspace:st},gl=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
183
182
|
|
|
184
183
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
185
184
|
|
|
186
|
-
${t}`},default:()=>""})});var
|
|
185
|
+
${t}`},default:()=>""})});var pl=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
|
|
187
186
|
|
|
188
187
|
_Example: “Tell me about this map”_
|
|
189
188
|
_Example: “List all layers in this map”_
|
|
@@ -196,16 +195,16 @@ ${t}`},default:()=>""})});var Tl=String.raw`- **help** — Enables users to ask
|
|
|
196
195
|
|
|
197
196
|
IF the user asks map related queries, but those that are not performed by any of the agents, call this agent so we can respond accordingly.
|
|
198
197
|
_Example: "Create a chart"_
|
|
199
|
-
_Example: "Create a table"_`;var
|
|
198
|
+
_Example: "Create a table"_`;var wl=g.Root({messages:g({reducer:L,default:()=>[]}),outputMessage:g({reducer:(e="",r)=>{let t=typeof r=="string"?r.trim():"";if(!t)return e;let a=e.trim();if(!a)return t;if(a===t)return e;let o=a.split(`
|
|
200
199
|
|
|
201
200
|
`);return o[o.length-1]?.trim()===t?e:`${e}
|
|
202
201
|
|
|
203
|
-
${t}`},default:()=>""}),intent:
|
|
204
|
-
Explanation: ${i}`}async function
|
|
205
|
-
Explanation: ${s}`}async function
|
|
202
|
+
${t}`},default:()=>""}),intent:g({reducer:(e,r)=>r})}),H={conversationId:""},en=["linkChartView"],tn=["knowledgeGraph"];function te(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=en.filter(a=>!(a in r));if(t.length)throw new Error(`Link Chart context missing: ${t.join(", ")}`);return r}function Ee(e){let r=e?.configurable?.context;if(!r||typeof r!="object")throw new Error("ArcgisKnowledgeAgent context missing");let t=tn.filter(a=>!(a in r));if(t.length)throw new Error(`Knowledge Graph context missing: ${t.join(", ")}`);return r}var de=class{constructor(r){this.dataModel=r,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ue.fromDataModel(r)}},ue=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(r){let t=new e;for(let a of r.entityTypes)t.entityTypes.push(G.fromEntityType(a));for(let a of r.relationshipTypes)t.relationshipTypes.push(he.fromRelationshipType(a));return t.identifierInfo={mappingInfo:{identifierMapsTo:rn(r.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:r.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},t.spatialReference=JSON.parse(JSON.stringify(r.spatialReference)),t}},G=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(r){let t=new e;t.name=r.name,t.alias=r.alias?r.alias:void 0,t.role=an(r.role);for(let a of r.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:on(a.role),geometryDef:a.fieldType==="esriFieldTypeGeometry"?{geometryType:a.geometryType??"esriGeometryAny",hasM:a.hasM?a.hasM:void 0,hasZ:a.hasZ?a.hasZ:void 0}:void 0};t.properties.push(o)}return t}},he=class extends G{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(r){let t=G.fromEntityType(r);t.observedEndPoints=[];for(let a of r.endPoints)t.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return t}},rn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},an=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function on(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"}}async function nn(e,r,t,a){let{graphQuery:o,explanation:i}=await Ie(e,r,t,a);return`Generated Graph Query: ${o}
|
|
203
|
+
Explanation: ${i}`}async function Ie(e,r,t,a){let o={message:e,context:new de(r)};H.conversationId&&(o.conversationId=H.conversationId),await h({text:"Attempting to generate a cypher query from your prompt..."},a);let i=await Re(`${t}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Me.findCredential(P.getDefault().url)?.token??""}});if(i.httpStatus!==200)throw new Error(`Graph query service returned an error: ${i.httpStatus}`,{cause:i.data});H.conversationId||(H.conversationId=i.data.conversationId);let s=!1,l=Date.now(),c=i.data.sequenceNumber,d="",u="",m=1;for(;!s;){await new Promise(y=>setTimeout(y,1e3)),await h({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,m)}`},a),m=m%3+1;let f=await Re(`${t}/chat`,{method:"post",body:JSON.stringify({conversationId:i.data.conversationId,inquiryId:i.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Me.findCredential(P.getDefault().url)?.token??""}});if(f.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${f.httpStatus}`,{cause:f.data});if(f.data.context)d=f.data.context.graphQuery,u=f.data.message||"";else if(!f.data.hasMore)s=!0;else if(Date.now()-l>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=f.data.sequenceNumber}return{graphQuery:d,explanation:u}}function Z(e,r){if(!(!e||typeof e!="object")){if(ln(e))for(let t of e.path)Z(t,r);else if(sn(e))r.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let t of e)Z(t,r);else if(cn(e))for(let t of Object.values(e.properties??{}))Z(t,r)}}function sn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function ln(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function cn(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function dn(e,r){let t=[];for(let a of[...r.dataModel.entityTypes,...r.dataModel.relationshipTypes]){let o=e.getMemberIdsByType(a.name);for(let i of o)t.push({id:i,typeName:a.name})}return t}var un=async e=>{let r=new Map,t=e.resultRowsStream.getReader();for(;;){let{done:a,value:o}=await t.read();if(a)break;for(let i of o)for(let s of i)Z(s,r)}return Array.from(r.values())};async function hn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await Ie(e,r.dataModel,t,o);await h({text:`Attempting to execute query: ${i.substring(0,500)}${i.length>500?"...":""}`},o);let l=await Rt(r,new Ue({openCypherQuery:i}),{signal:o?.signal,timeout:o?.timeout}),c=await un(l);return await h({text:`Query Results parsed into ${c.length} unique relationships and entities. Atempting to add to link chart...`},o),await a.map.addRecords(c),`Link Chart updated successfully. Cypher Query used: ${i}
|
|
204
|
+
Explanation: ${s}`}async function mn({prompt:e},r){let{knowledgeGraph:t}=Ee(r),{linkChartView:a}=te(r),o=P.getDefault().helperServices,i=await F("arcgis_knowledge_current_lc_context"),s=dn(a.map,t),l=`${e}
|
|
206
205
|
|
|
207
|
-
${i}${JSON.stringify(s)}`;return await
|
|
208
|
-
Explanation: ${s}`}async function
|
|
206
|
+
${i}${JSON.stringify(s)}`;return await hn(l,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var fn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),bl=p(mn,{name:"addRecords",description:"Adds records (entities or relationships) to the current 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 records to be added to the link chart. The user should have explicitly requested to add records to the current link chart from their prompt.",schema:fn});async function yn(e,r){return await r.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function gn({layout:e},r){let{linkChartView:t}=te(r);return await yn(e,t)}var pn=n.object({layout:n.enum(["organic-standard","organic-community","basic-grid","hierarchical-bottom-to-top","radial-root-centric","tree-left-to-right","geographic-organic-standard","chronological-mono-timeline","chronological-multi-timeline"]).describe("The layout mode to apply to the link chart. The value must be one of the following: organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline, chronological-multi-timeline")}),vl=p(gn,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:pn});function wn(e,r){return r.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function bn({setting:e},r){let{linkChartView:t}=te(r);return wn(e,t)}var vn=n.object({setting:n.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Sl=p(bn,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:vn});async function Sn(e,r,t,a,o){let{graphQuery:i,explanation:s}=await Ie(e,r.dataModel,t,o);await h({text:`Attempting to create link chart from derived query: ${i}`},o);let l=await Mt.fromCypherQuery(r,new Ue({openCypherQuery:i}));return await h({text:"Link chart created successfully, loading..."},o),a.map=l,await l.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart: ${i}
|
|
207
|
+
Explanation: ${s}`}async function Tn({prompt:e},r){let{knowledgeGraph:t}=Ee(r),{linkChartView:a}=te(r),o=P.getDefault().helperServices;return await Sn(e,t,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,r)}var xn=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visulalization.")}),Tl=p(Tn,{name:"createLinkChart",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:xn});async function En({prompt:e},r){let{knowledgeGraph:t}=Ee(r),a=P.getDefault().helperServices;return await nn(e,t.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,r)}var In=n.object({prompt:n.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),xl=p(En,{name:"generateCypher",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:In});var El=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).
|
|
209
208
|
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.
|
|
210
209
|
For link charts, the agent enables users to interact with a link chart by adding new entities (also called nodes) or relationships (also called edges), removing existing entities or relationships,
|
|
211
210
|
expanding the graph from particular entities, finding relationships between specified entities on the link chart and adding them to the link chart, finding all relationships
|
|
@@ -237,4 +236,4 @@ _example: "Find all the products supplied by Supplier X and add them to my visua
|
|
|
237
236
|
_example: "Expand the link chart from 'Entity D' to show its direct connections"_
|
|
238
237
|
_example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
|
|
239
238
|
_example: "Connect Emma and Rob on the link chart if there is a relationship between them"
|
|
240
|
-
_example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:
|
|
239
|
+
_example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:hl,b:ml,c:fl,d:yl,e:Pe}},"Graphic","geometry/Point","geometry/Extent","symbols/SimpleMarkerSymbol","rest/locator","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","rest/support/Query","geometry/operators/bufferOperator","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","rest/knowledgeGraph/GraphQueryStreaming","request","identity/IdentityManager","portal/Portal","rest/knowledgeGraphService","WebLinkChart",a)
|