@arcgis/ai-components 5.1.0-next.87 → 5.1.0-next.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/4IESERNN.js +2 -0
- package/dist/cdn/{GJQVEIZF.js → 7AAA466K.js} +1 -1
- package/dist/cdn/B3E2XBTX.js +2 -0
- package/dist/cdn/E2MBKDZ2.js +2 -0
- package/dist/cdn/EUNEQNYC.js +2 -0
- package/dist/cdn/JEO7CHZM.js +2 -0
- package/dist/cdn/{KWBMH7LU.js → K35QKERW.js} +5 -0
- package/dist/cdn/KCSGJGUQ.js +2 -0
- package/dist/cdn/{FTUILS6R.js → KHCTRS6Z.js} +21 -21
- package/dist/cdn/O3Y4IPK5.js +2 -0
- package/dist/cdn/SOJ4DKGV.js +226 -0
- package/dist/cdn/TD74ZINA.js +2 -0
- package/dist/cdn/{NCMEKPIM.js → TFP2SGKU.js} +1 -1
- package/dist/cdn/{4TY43HO3.js → UTCN4YUI.js} +1 -1
- package/dist/cdn/VDGRXEK7.js +2 -0
- package/dist/cdn/VHOF6SUZ.js +120 -0
- package/dist/cdn/{2FQTU6HL.js → WBVJLC7F.js} +1 -1
- package/dist/cdn/X2GSYADT.js +2 -0
- package/dist/cdn/YUZDB6IX.js +2 -0
- package/dist/cdn/index.js +1 -1
- package/dist/cdn/main.css +1 -1
- package/dist/chunks/slottableRequestUtils.js +11 -0
- package/dist/components/arcgis-assistant/customElement.d.ts +16 -1
- package/dist/components/arcgis-assistant/customElement.js +116 -112
- package/dist/components/arcgis-assistant/index.js +2 -0
- package/dist/components/arcgis-assistant/types.d.ts +2 -4
- package/dist/components/arcgis-assistant-message/customElement.js +26 -12
- package/dist/components/arcgis-assistant-message/index.js +0 -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/dist/index.d.ts +0 -14
- package/dist/loader.js +0 -1
- package/dist/types/lumina.d.ts +1 -11
- package/dist/types/preact.d.ts +1 -13
- package/dist/types/react.d.ts +1 -15
- package/dist/types/stencil.d.ts +1 -11
- package/package.json +6 -6
- package/dist/cdn/3IWT4SEI.js +0 -2
- package/dist/cdn/AAOF7JQT.js +0 -2
- package/dist/cdn/ERCMPLS4.js +0 -82
- package/dist/cdn/HLDIWEWD.js +0 -2
- package/dist/cdn/KJFC3ZEP.js +0 -2
- package/dist/cdn/MDPF56RC.js +0 -2
- package/dist/cdn/OFWYCHDQ.js +0 -2
- package/dist/cdn/QTH2DYCO.js +0 -2
- package/dist/cdn/UWXD5PFQ.js +0 -2
- package/dist/cdn/VSZNNBU6.js +0 -2
- package/dist/cdn/XMI2K6YV.js +0 -2
- package/dist/cdn/ZIER3BNM.js +0 -226
- package/dist/components/arcgis-assistant-message/customElement.d.ts +0 -18
- package/dist/components/arcgis-assistant-message/index.d.ts +0 -1
- package/dist/components/arcgis-assistant-message-content/customElement.d.ts +0 -12
- package/dist/components/arcgis-assistant-message-content/customElement.js +0 -62
- package/dist/components/arcgis-assistant-message-content/index.d.ts +0 -1
- package/dist/components/arcgis-assistant-message-content/index.js +0 -4
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import{a as o}from"./YUZDB6IX.js";import"./B3E2XBTX.js";import"./YGW7TUNX.js";import{g as a,h as e,n as i,v as c,y as n}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";var r=a`.actions{display:flex;flex-direction:row;gap:var(--calcite-spacing-xs)}`,t=class extends c{constructor(){super(...arguments),this._messages=o({blocking:!0}),this.feedbackEnabled=!1,this.arcgisFeedback=i()}static{this.properties={feedbackEnabled:5,message:0}}static{this.styles=r}_handleFeedback(s){this.message&&(this.message.feedback=this.message.feedback?.positive===s?void 0:{positive:s},this.arcgisFeedback.emit(this.message),this.requestUpdate())}_getFeedback(){return this.message?.feedback?.positive}_renderThumbsUpButton(){return e`<calcite-action id=action-thumbs-up icon=thumbs-up scale=s .active=${this._getFeedback()===!0} @click=${()=>this._handleFeedback(!0)} text></calcite-action><calcite-tooltip reference-element=action-thumbs-up overlay-positioning=fixed placement=bottom><span>${this._messages.thumbsUpLabel}</span></calcite-tooltip>`}_renderThumbsDownButton(){return e`<calcite-action id=action-thumbs-down icon=thumbs-down scale=s .active=${this._getFeedback()===!1} @click=${()=>this._handleFeedback(!1)} text></calcite-action><calcite-tooltip reference-element=action-thumbs-down overlay-positioning=fixed placement=bottom><span>${this._messages.thumbsDownLabel}</span></calcite-tooltip>`}render(){return this.feedbackEnabled&&!this.message?.error?e`<div class="actions">${this._renderThumbsUpButton()}${this._renderThumbsDownButton()}</div>`:null}};n("arcgis-assistant-message-feedback",t);export{t as ArcgisAssistantMessageFeedback};
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import a from"./KHCTRS6Z.js";import{Bb as H,Fb as A,L as O,M as oe,Q as ne,R as V,Za as N,_a as y,a as M,b as T,g as ve,j as W,k as K,kb as g,q as Se,qb as Te,u as xe}from"./PLPJJRCP.js";export default $arcgis.t(([dt,pe,je,ut,{addressToLocations:mt},D,se,pt,De,Oe,{formatDateOnly:ht,convertDateFormatToIntlOptions:Z,formatTimeOnly:ft,formatDate:_e},Ve,Pe,gt,yt,{createRenderer:wt},{getSchemesByTag:bt,getSchemes:vt},{getBackgroundColorTheme:Ce},{createAgeRenderer:St,createContinuousRenderer:xt},{getSchemesByTag:he},{createContinuousRenderer:Tt},{createRenderer:Et},{getSchemesByTag:It},{createRenderer:kt},{getSchemesByTag:$t},{createRenderer:_t},{getSchemesByTag:Ct},{createRenderer:Nt},{getSchemesByTag:Ft},{createAgeRenderer:Mt,createContinuousRenderer:At},{createRenderer:qt},{getSchemesByTag:Rt},Ge,Ne,Fe,{executeQueryStreaming:Lt},zt,{a:l,b:h,c:I,e:Ee,f:Ie,g:j}])=>{var $e=e=>Array.isArray(e)&&e.every(O),it=e=>typeof e=="object"&&e!=null&&"messages"in e&&$e(e.messages),st=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e,q=class extends Te{tools;handleToolErrors=!0;trace=!1;constructor(e,t){let{name:r,tags:a,handleToolErrors:o}=t??{};super({name:r,tags:a,func:(n,s)=>this.run(n,s)}),this.tools=e,this.handleToolErrors=o??this.handleToolErrors}async runTool(e,t){let r=this.tools.find(a=>a.name===e.name);try{if(r===void 0)throw new Error(`Tool "${e.name}" not found.`);let a=await r.invoke({...e,type:"tool_call"},t);return O(a)&&a.getType()==="tool"||K(a)?a:new oe({status:"success",name:r.name,content:typeof a=="string"?a:JSON.stringify(a),tool_call_id:e.id})}catch(a){if(!this.handleToolErrors||xe(a))throw a;return new oe({status:"error",content:`Error: ${a.message}
|
|
3
|
+
Please fix your mistakes.`,name:e.name,tool_call_id:e.id??""})}}async run(e,t){let r;if(st(e))r=[await this.runTool(e.lg_tool_call,t)];else{let n;if($e(e))n=e;else if(it(e))n=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let s=new Set(n.filter(c=>c.getType()==="tool").map(c=>c.tool_call_id)),i;for(let c=n.length-1;c>=0;c-=1){let d=n[c];if(V(d)){i=d;break}}if(i==null||!V(i))throw new Error("ToolNode only accepts AIMessages as input.");r=await Promise.all(i.tool_calls?.filter(c=>c.id==null||!s.has(c.id)).map(c=>this.runTool(c,t))??[])}if(!r.some(K))return Array.isArray(e)?r:{messages:r};let a=[],o=null;for(let n of r)K(n)?n.graph===W.PARENT&&Array.isArray(n.goto)&&n.goto.every(s=>ve(s))?o?o.goto.push(...n.goto):o=new W({graph:W.PARENT,goto:n.goto}):a.push(n):a.push(Array.isArray(e)?[n]:{messages:[n]});return o&&a.push(o),a}};var ji=g.Root({llmInputMessages:g({reducer:(e,t)=>H([],t),default:()=>[]})});var B=(e,t)=>({...e,...t}),Q=(e="",t)=>{let r=typeof t=="string"?t.trim():"";if(!r)return e;let a=e.trim();if(!a)return r;if(a===r)return e;let o=a.split(`
|
|
4
|
+
|
|
5
|
+
`);return o[o.length-1]?.trim()===r?e:`${e}
|
|
6
|
+
|
|
7
|
+
${r}`},$=(e,t)=>t??e,Be=g.Root({agentExecutionContext:g({reducer:B,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:g({reducer:Q,default:()=>""}),summary:g({reducer:$,default:()=>""}),status:g({reducer:$}),intent:g({reducer:$}),vectorSearchLayerResults:g({reducer:$,default:()=>[]}),vectorSearchFieldResults:g({reducer:$}),navigationInternalState:g({reducer:$,default:()=>({toolCallMessage:void 0})})});async function jt(e,t){let r=D.getDefault().helperServices,a=r.geocode.find(E=>E.name==="ArcGIS World Geocoding Service")??r.geocode[0];if(!a)throw new Error("No geocoding service found in helperServices.");let o=a.url,n=`${se.assetsPath?.endsWith("/")?se.assetsPath:`${se.assetsPath}/`}esri/images/search/search-symbol-32.png`,s=(await mt(o,{address:{SingleLine:e},outFields:["Match_addr"]}))?.[0];if(!s?.extent)throw new Error(`Could not find location for: ${e}`);let{xmin:i,ymin:c,xmax:d,ymax:u,spatialReference:m}=s.extent,p=new je({xmin:i,ymin:c,xmax:d,ymax:u,spatialReference:m}),b=(i+d)/2,w=(c+u)/2,f=new pe({x:b,y:w,spatialReference:m}),v=new ut({url:n,width:24,height:24}),S=new dt({geometry:f,symbol:v});return t.graphics.removeAll(),t.graphics.add(S),await t.goTo(p),`Successfully zoomed to: ${e}. Location coordinates: x=${b}, y=${w}, wkid=${m.wkid}`}var Dt=["mapView"];function _(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("NavigationAgent context missing");let r=Dt.filter(a=>!(a in t));if(r.length)throw new Error(`NavigationAgent context missing: ${r.join(", ")}`);return t}async function Ot({address:e},t){let{mapView:r}=_(t);return await jt(e,r)}var Vt=l.object({address:l.string().describe("The full address or place name to locate.")}),Pt=y(Ot,{name:"goToAddress",description:"Geocodes an address using Esri's World Geocoding Service and zooms the map to that location.",schema:Vt});async function Gt(e,t){let r=t.map.bookmarks;if(!r||r.length===0)throw new Error("No bookmarks found in the map.");let a=r.find(n=>n.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 t.goTo(o),`Navigated to bookmark: ${e}`}async function Bt({bookmarkName:e},t){let{mapView:r}=_(t);return await Promise.resolve(Gt(e,r))}var Qt=N.object({bookmarkName:N.string().describe("The name of the bookmark to navigate to.")}),Ut=y(Bt,{name:"goToBookmark",description:"Go to the extent of the bookmark with the given name.",schema:Qt});async function Wt(e,t,r){let a=r.map?.allLayers.find(n=>n.id===e);if(!a)return`Error: Layer with id ${e} not found`;let o=a.createQuery();o.where=t??"1=1";try{let{extent:n,count:s}=await a.queryExtent(o);if(s===0)return`No features found in ${a.title} matching: ${t}`;if(n)await r.goTo(n);else return`Error: Unable to determine extent for ${a.title}`;return`Successfully zoomed to ${s} feature(s) in ${a.title}`}catch(n){return console.error("Error in goToFeatures:",n),`Error: ${n instanceof Error?n.message:"Unknown error"}`}}async function Kt({layerId:e,where:t},r){let{mapView:a}=_(r);return await Wt(e,t,a)}var Ht=N.object({layerId:N.string().describe("The layerId of the layer to zoom to."),where:N.string().describe("The sql-92 where clause used to query features to zoom to")}),Zt=y(Kt,{name:"goToFeatures",description:"Go to the features that match the given filter related to the given layerId.",schema:Ht});async function Jt(e){let t=new je({xmin:-180,ymin:-90,xmax:180,ymax:90,spatialReference:{wkid:4326}}).expand(.7);return await e.goTo(t),"Successfully zoomed to world extent"}async function Yt(e,t){let{mapView:r}=_(t);return await Jt(r)}var Xt=N.object({}),er=y(Yt,{name:"goToFullExtent",description:"Zooms the map to the full world extent using Esri's Geocoding Service.",schema:Xt});async function tr(e){let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;if(t)await e.goTo(t);else throw new Error("Initial extent is undefined");return"Successfully zoomed to home extent"}async function rr(e,t){let{mapView:r}=_(t);return await tr(r)}var ar=l.object({}),or=y(rr,{name:"goToHomeExtent",description:"Go to the initial web map view extent",schema:ar});async function nr(e,t){await t.when();let r=t.map?.allLayers.find(o=>o.id===e);if(!r)return console.warn(`[goToLayer] No matching FeatureLayer found for: ${e}`),`Could not find layer for: ${e}`;let a;return(r.type==="link-chart"||r.type==="knowledge-graph-sublayer")&&t.map?.activeLinkChartLayer?a=t.map.diagramNodesExtent:a=r.fullExtent,a?(await t.goTo(a),r.visible=!0,`Successfully zoomed to: ${r.title??""}`):"Layer has no defined extent. Cannot zoom to layer."}async function ir({layerId:e},t){let{mapView:r}=_(t);return await nr(e,r)}var sr=N.object({layerId:N.string().describe("The id of the layer to navigate to")}),lr=y(ir,{name:"goToLayer",description:"Zooms the map view to the full extent of the top matching layer.",schema:sr});async function cr(e,t){return await t.goTo({scale:e}),`Successfully zoomed to: ${e}`}async function dr({scale:e},t){let{mapView:r}=_(t);return await cr(e,r)}var ur=l.object({scale:l.number().describe("The map scale of the view to go to.")}),mr=y(dr,{name:"goToScale",description:"Go to the specified view scale.",schema:ur});async function pr(e,t,r){let a={target:new pe({longitude:e.longitude,latitude:e.latitude,spatialReference:{wkid:4326}})};return r?.zoom!==void 0&&(a.zoom=r.zoom),r?.scale!==void 0&&(a.scale=r.scale),await t.goTo(a),`Successfully navigated to: ${[`(${e.latitude}\xB0, ${e.longitude}\xB0)`,r?.zoom!==void 0?`zoom ${r.zoom}`:"",r?.scale!==void 0?`scale 1:${r.scale}`:""].filter(Boolean).join(", ")}`}async function hr({center:e,zoom:t,scale:r},a){let{mapView:o}=_(a);return await pr(e,o,{zoom:t,scale:r})}var fr=l.object({center:l.object({longitude:l.number().describe("The longitude (x-coordinate) of the point to navigate to."),latitude:l.number().describe("The latitude (y-coordinate) of the point to navigate to.")}),zoom:l.number().optional().describe("The zoom level. Higher values = more zoomed in."),scale:l.number().optional().describe("The map scale. Alternative to zoom. Smaller numbers = more zoomed in.")}),gr=y(hr,{name:"goToViewpoint",description:"Go to the specified viewpoint. This can contain a combination of scale, center, zoom, etc.",schema:fr});async function yr(e,t){return await t.goTo({zoom:e}),`Successfully zoomed to: ${e}`}async function wr({zoom:e},t){let{mapView:r}=_(t);return await yr(e,r)}var br=l.object({zoom:l.number().min(1).max(20).describe("The zoom level of the view to go to.")}),vr=y(wr,{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:br}),fe=[Pt,Ut,Zt,er,or,lr,mr,gr,vr],Me=Object.assign({"../agents/arcgisKnowledge/prompts/arcgis_knowledge_current_lc_context.md":()=>import("./LSGRWCAO.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_intent_prompt.md":()=>import("./KKHKKCYH.js").then(e=>e.default),"../agents/arcgisKnowledge/prompts/arcgis_knowledge_tool_prompt.md":()=>import("./KQ6LEQHH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_filter_prompt.md":()=>import("./MZJGADGH.js").then(e=>e.default),"../agents/dataExploration/prompts/data_explore_query_prompt.md":()=>import("./5PT7ZFXF.js").then(e=>e.default),"../agents/dataExploration/prompts/summarize_query_response_prompt.md":()=>import("./K35QKERW.js").then(e=>e.default),"../agents/help/prompts/help_prompt.md":()=>import("./ESTSYVJP.js").then(e=>e.default),"../agents/layerStyling/prompts/layer_styling_prompt.md":()=>import("./CFT5BBC6.js").then(e=>e.default),"../agents/navigation/prompts/navigation_intent_prompt.md":()=>import("./SFREIREB.js").then(e=>e.default),"../agents/navigation/prompts/navigation_tool_prompt.md":()=>import("./DMLSCJAM.js").then(e=>e.default)});async function R(e){let t=Object.entries(Me).find(([r])=>r.endsWith(`/${e}.md`));if(!t)throw new Error(`Prompt not found: ${e}
|
|
8
|
+
Available prompts:
|
|
9
|
+
${Object.keys(Me).join(`
|
|
10
|
+
`)}`);return await t[1]()}async function Sr(e,t){let r=await R("navigation_tool_prompt"),{mapView:a}=_(t),o=a.map,n=e.vectorSearchLayerResults?.length>0?e.vectorSearchLayerResults.map((f,v)=>`${v+1}. layerId=${f.id} | title=${f.title??""} | name=${f.name??""} | score=${f.score.toFixed(2)}`).join(`
|
|
11
|
+
`):"",s=e.vectorSearchFieldResults?.length>0?JSON.stringify(e.vectorSearchFieldResults,null,2):"",i=e.intent==="goToBookmark"&&o.bookmarks?.length?`Available bookmarks:
|
|
12
|
+
${JSON.stringify(o.bookmarks,null,2)}`:"",c=(e.intent==="goToLayer"||e.intent==="goToFeatures")&&e.vectorSearchLayerResults?.length?`Candidate layers:
|
|
13
|
+
${n}`:"",d=e.intent==="goToFeatures"&&e.vectorSearchFieldResults?.length?`Candidate fields:
|
|
14
|
+
${s}`:"",u={intent:e.intent,bookmarksSection:i,layersSection:c,fieldsSection:d,currentZoom:a.zoom,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},m=await j({promptText:r,modelTier:"advanced",inputVariables:u,tools:fe}),p=(m.tool_calls?.length??0)>0,b=typeof m.text=="string"?m.text.trim():"",w=b.length>0;return{...e,navigationInternalState:{...e.navigationInternalState,toolCallMessage:p?m:void 0},outputMessage:p?e.outputMessage:b,status:p?e.status:w?"success":"failed"}}var U=(e,t=300)=>{let r=e.replace(/\s+/gu," ").replace(/[*_`#>\-]/gu,"").trim();return r.length>t?`${r.slice(0,t)}...`:r};async function xr(e,t){let r=new q(fe);try{let a=e.navigationInternalState.toolCallMessage;if(!a)throw new Error("navigationToolCalling: missing navigationInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
|
|
15
|
+
`);return await h({text:`Finished executing navigation tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?U(o):"Navigation executed.",navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await h({text:`Navigation tool execution failed: ${o}`},t),{...e,outputMessage:`Navigation tool execution failed: ${o}`,status:"failed",summary:`Navigation tool execution failed: ${o}`,navigationInternalState:{...e.navigationInternalState,toolCallMessage:void 0}}}}async function Tr(e,t){let r=await R("navigation_intent_prompt"),{mapView:a}=_(t),o=fe.map(m=>({name:m.name,description:m.description,schema:m.schema})),n=a.map,s=n.bookmarks?.length?`Available bookmarks:
|
|
16
|
+
${JSON.stringify(n.bookmarks,null,2)}`:"",i={tools:o.map(({name:m,description:p,schema:b})=>`${m}: ${p}, ${JSON.stringify(b)}`).join(`
|
|
17
|
+
`),bookmarks:s,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},c=l.object({intent:l.string()}),d=await Ie({promptText:r,inputVariables:i,schema:c}),u=typeof d.intent=="string"?d.intent.trim().replace(/^"|"$/gu,""):"";return{...e,intent:u||""}}var x=(e,t)=>{let r=e?.configurable?.services?.[t];if(r==null)throw new Error(`${t} missing in config.configurable.services`);return r},Er=.7,Ir=async(e,t)=>{try{await h({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=(await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Er,embeddingCache:o})).map(({id:i,score:c})=>{let d=a.get(i)?.layerItem;return{id:i,title:d?.title,name:d?.name??void 0,score:c}}),s;return n.length>0?s=`Vector search completed. Matching layers:
|
|
18
|
+
${n.map(i=>`- layerId=${i.id} | title=${i.title??""} | name=${i.name??""} | score=${i.score.toFixed(2)}`).join(`
|
|
19
|
+
`)}`:s="Vector search completed. No matching layers found.",await h({text:s},t),{...e,vectorSearchLayerResults:n}}catch(r){throw await h({text:`Error during vector search layers: ${r instanceof Error?r.message:String(r)}`},t),r}},Ae=.7,kr=10,$r=async(e,t)=>{try{await h({text:`Similarity search to find fields: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=e.vectorSearchLayerResults?.map(c=>c.id)??[];if(n.length===0)return await h({text:"No candidate layers for field search"},t),e;let s=(await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:n,minScore:Ae,topResults:kr,embeddingCache:o})).map(({layerId:c,results:d})=>{let u=a.get(c)?.fieldRegistry;return{layerId:c,layerName:a.get(c)?.layerItem.name,results:d.map(m=>{let p=u?.get(m.name);return{name:m.name,score:m.score,type:p?.type,alias:p?.alias,description:p?.description,statistics:p?.statistics}})}}),i;return s.length>0?i=`Vector search completed. Matching layers and fields:
|
|
20
|
+
${s.map(c=>`${c.layerName??c.layerId}:
|
|
21
|
+
${c.results.map(d=>` - ${d.name} (${d.score.toFixed(2)})`).join(`
|
|
22
|
+
`)}`).join(`
|
|
23
|
+
`)}`:i=`No vector search field results found for score over ${Ae}.`,await h({text:i},t),{...e,vectorSearchFieldResults:s}}catch(r){throw await h({text:`Error during vector search fields: ${r instanceof Error?r.message:String(r)}`},t),r}},te=(e,t)=>(r,a)=>{let o=a?.configurable?.services;for(let n of e)if(!o?.[n])throw new Error(`${t} requires services.${n} to be available.`);return r},_r=(e,t)=>te(["layerSearch","layersAndFieldsRegistry"],"Navigation Agent")(e,t),Cr=()=>new A(Be).addNode("requireNavigationServices",_r).addNode("intentLLM",Tr).addNode("vectorSearchLayers",Ir).addNode("vectorSearchFields",$r).addNode("agent",Sr).addNode("tools",xr).addEdge(M,"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",T),Nr=String.raw`- **navigation** — Enables users to interact with the map by navigating to specific locations, layers, features, or extents.
|
|
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 "show me...", that is meant to be handled by another agent. If the query is about where a certain address is, call this agent.
|
|
25
|
+
|
|
26
|
+
Supported actions:
|
|
27
|
+
- **Zooming**: Adjust the map's zoom level (e.g., "Zoom to level 10", "Zoom in").
|
|
28
|
+
- **Viewpoints**: Navigate to a specific center point with optional zoom or scale (e.g., "Center the map on San Francisco at zoom level 16").
|
|
29
|
+
- **Scales**: Set the map to a specific scale (e.g., "Set the map scale to 1:50,000").
|
|
30
|
+
- **Layers**: Zoom to the full extent of a specific layer (e.g., "Go to the water mains layer"). For the purposes of link charts, if the user requests to go to the extent of a link chart or the entities/nodes within it, that should be treated as a request to use the goToLayer tool on the link chart layer
|
|
31
|
+
- **Features**: Zoom to features in a layer that match a filter (e.g., "Zoom to all schools in the city").
|
|
32
|
+
- **Bookmarks**: Navigate to a predefined bookmark extent (e.g., "Go to the Downtown bookmark").
|
|
33
|
+
- **Extents**: Reset to the initial web map extent or zoom to the full world extent (e.g., "Reset the map", "Zoom to the full world extent").
|
|
34
|
+
- **Addresses**: Zoom to an address or place name (e.g., "Zoom to 1600 Pennsylvania Ave").
|
|
35
|
+
|
|
36
|
+
_Example: “Zoom to Texas”_
|
|
37
|
+
_Example: “Go to the water mains layer”_
|
|
38
|
+
_Example: “Zoom to to the extent of my link chart”_
|
|
39
|
+
_Example: “Center the map on San Francisco at scale 50000”_
|
|
40
|
+
_Example: “Zoom to the features in the schools layer where city = 'Austin'”_
|
|
41
|
+
_Example: “Go to the Downtown bookmark”_
|
|
42
|
+
_Example: “Where is Mount Rainier?”_`,Os={id:"navigation",name:"Navigation Agent",description:Nr,createGraph:Cr,workspace:Be},Qe=g.Root({agentExecutionContext:g({reducer:B,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:g({reducer:Q,default:()=>""}),summary:g({reducer:$,default:()=>""}),status:g({reducer:$}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),queryResponse:g(),dataExplorationMessages:g({reducer:H,default:()=>[]})}),Fr=async(e,t)=>(await h({text:"Exiting Data Exploration agent"},t),e),ge=async(e,t)=>{let r=e.tool_calls??[];if(r.length===0){await h({text:`LLM did not request any tool calls: ${String(e?.content)}`},t);return}await Promise.all(r.map(async a=>await h({text:`LLM invoked ${a.name} tool with arguments: ${JSON.stringify(a.args,null,2)}`},t)))},Mr=["mapView"];function L(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("DataExplorationAgent context missing");let r=Mr.filter(a=>!(a in t));if(r.length)throw new Error(`DataExplorationAgent context missing: ${r.join(", ")}`);return t}var Ar=e=>{let t=e.map?.allLayers.filter(a=>a.type==="feature"),r=0;return t?.forEach(a=>{let o=a;o.featureEffect&&(o.featureEffect=null,r++)}),r>0?`Cleared filters from ${r} layer(s). View unchanged.`:"No active filters to clear. View unchanged."},qr=async(e,t)=>{let{mapView:r}=L(t);return Ar(r)},Rr=y(qr,{name:"clearFilters",description:"Clears all feature effects/filters from the map but does NOT change the current view. Use when user says 'clear filters', 'reset filters', 'remove filters', 'show all features', or wants to remove emphasis without navigating anywhere.",schema:l.object({})}),Lr=async e=>{e.map?.allLayers.filter(r=>r.type==="feature")?.forEach(r=>{let a=r;a.featureEffect&&(a.featureEffect=null)});let t=e.map.initialViewProperties?.viewpoint?.targetGeometry;return t?(await e.goTo(t),"Cleared all filters and returned to home extent."):"Cleared all filters. Could not determine home extent."},zr=async(e,t)=>{let{mapView:r}=L(t);return await Lr(r)},jr=y(zr,{name:"resetMap",description:"Clears all feature effects/filters from the map AND zooms to the home extent (initial map view). Use when user says 'reset map', 'reset the map', 'start over', or wants to both clear filters and return to the initial view.",schema:l.object({})});function X(e){return"point"in e&&e.point!==void 0}function P(e){return"layerId"in e&&e.layerId!==void 0}var re=async(e,t)=>{if(X(e)){let{point:r}=e;return{geometry:new pe({x:r.x,y:r.y,spatialReference:r.spatialReference?{wkid:r.spatialReference.wkid}:t.spatialReference})}}if(P(e)){let r=t.map?.allLayers.find(o=>o.id===e.layerId);if(!r)return{error:`Could not find geometry layer with ID: ${e.layerId}`};let a=r.title??r.id;try{let o=await r.queryFeatures({where:e.where,returnGeometry:!0,outSpatialReference:t.spatialReference});if(!o.features.length)return{error:`No features found in geometry layer "${a}" with the specified where clause: ${e.where}`};let n;if(o.features.length===1){let s=o.features[0].geometry;if(!s)return{error:"The geometry of the first feature is undefined or null."};n=s}else{let s=o.features.map(c=>c.geometry),i=Oe.executeMany(s);if(!i)return{error:"Failed to create a combined geometry."};n=i}return n.spatialReference||(n.spatialReference=t.spatialReference),{geometry:n}}catch(o){return{error:`Failed to query geometry: ${String(o)}`}}}return{error:"Invalid geometry configuration provided"}},Dr=async(e,t,r,a,o,n)=>{let s=e.map?.allLayers.find(c=>c.id===t);if(!s)return{success:!1,error:`Layer '${t}' not found.`};let i=s.createQuery();i.where=r??"1=1",a&&(i.geometry=a,i.spatialRelationship="intersects",o&&(i.distance=o),n&&(i.units=n));try{let{extent:c,count:d}=await s.queryExtent(i);return!c||d===0?{success:!1,error:`No features found for filter (where: ${i.where}${a?", spatial filter used":""})`}:(await e.goTo(c),{success:!0})}catch(c){return{success:!1,error:c instanceof Error?c.message:String(c)}}},Or=async(e,t,r,a,o,n)=>{let s=t.map?.allLayers.find(m=>m.id===e.layerId);if(!s)return`Could not find target layer with ID: ${e.layerId}`;let i;if(o){let m=await re(o,t);if("error"in m)return m.error;i=m.geometry}if(s.featureEffect=null,s.featureEffect=new pt({filter:new De({...e.objectIds?.length?{objectIds:e.objectIds}:{where:e.where},geometry:i,spatialRelationship:"intersects",distance:o?.distance,units:o?.units}),includedEffect:r,excludedEffect:a}),s.visible=!0,n)return`Applied feature effects to "${s.title??e.layerId}" within current map extent.`;let c=e.objectIds?.length?`${s.objectIdField} IN (${e.objectIds.join(",")})`:e.where,d=await Dr(t,e.layerId,c,i,o?.distance,o?.units),u=s.title??e.layerId;return d.success?`Applied feature effects to target layer "${s.title??e.layerId}"${o&&"layerId"in o?` using geometry from layer "${o.layerId}"`:""}.`:`Applied filter to "${u}" but no features matched. ${d.error}`},Vr=["feet","kilometers","meters","miles","nautical-miles","us-nautical-miles"],z=l.enum(Vr),Pr=async({targetLayer:e,geometryFilter:t,useCurrentExtent:r,includedEffect:a="drop-shadow(2px, 2px, 2px, gray)",excludedEffect:o="grayscale(100%) opacity(60%) blur(2px)"},n)=>{let{mapView:s}=L(n);return await Or(e,s,a,o,t,r)},Gr=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),Br=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),Qr=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer on which to set a feature effect."),where:l.string().describe("The SQL-92 where clause representing the features to emphasize."),objectIds:l.array(l.number()).optional().describe("Array of objectIds from a previous query result. Use this instead of a where clause when the query returned objectIds (e.g. top N results). If provided, takes precedence over where clause.")}),geometryFilter:l.union([Gr,Br]).optional().describe("Optional geometry-based filtering parameters for spatial queries."),useCurrentExtent:l.boolean().optional().describe("Set to true when the previous query used the current map extent as a spatial filter. This ensures the feature effect applies only to features visible in the current view. Default is false."),includedEffect:l.string().default("drop-shadow(2px, 2px, 2px, gray)").describe("The effect applied to features that meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified."),excludedEffect:l.string().default("grayscale(100%) opacity(60%) blur(2px)").describe("The effect applied to features that do not meet the filter requirements. Valid effects include: bloom, blur, brightness, contrast, drop-shadow, grayscale, hue-rotate, invert, opacity, saturate, and sepia. Prefer default unless specified.")}),Ur=y(Pr,{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}),ce=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Wr=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Kr=e=>{if(typeof e=="string"&&e)return e;let t=ce(e);return t?t.toISOString().slice(0,10):null},Ue=()=>{let e=new Date().getTimezoneOffset(),t=e<=0?"+":"-",r=Math.floor(Math.abs(e)/60).toString().padStart(2,"0"),a=(Math.abs(e)%60).toString().padStart(2,"0"),o=`${t}${r}:${a}`;return{userTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,userTimezoneOffset:o}},Hr=(e,t,r)=>{let a=t?.toLowerCase();if(a==="date-only"){let n=Kr(e);return n?ht(n,Z("short-date")):e}if(a==="time-only"){if(typeof e=="string"&&e)return ft(e,Z("long-time"));let n=ce(e);return n?_e(n,{...Z("long-time"),timeZone:"UTC"}):e}let o=ce(e);return o?_e(o,{...Z("short-date-short-time"),timeZone:Wr(r)}):e},We=(e,t,r)=>{if(e&&typeof e!="function"){let a="getField"in r&&r.getField?.(e),o=a&&"getFieldDomain"in r&&r.getFieldDomain?r.getFieldDomain(a.name):null;if(o?.type==="coded-value"){let n=o.codedValues.find(s=>s.code===t);return n?n.name:null}}return null},Zr=e=>!e||e==="system"?Intl.DateTimeFormat().resolvedOptions().timeZone:e==="unknown"?"UTC":e,Jr=e=>{if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e=="number"&&Number.isFinite(e)){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}if(typeof e=="string"&&e){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null},Yr=(e,t)=>{if(typeof e!="number")return e;let r={};t.minimumFractionDigits!==void 0&&(r.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(r.maximumFractionDigits=t.maximumFractionDigits),t.useGrouping==="always"?r.useGrouping=!0:t.useGrouping==="never"&&(r.useGrouping=!1);try{return new Intl.NumberFormat(void 0,r).format(e)}catch{return e}},Xr=(e,t,r)=>{let a=Jr(e);if(!a)return e;let o={};t.dateStyle?o.dateStyle=t.dateStyle:(t.year&&(o.year=t.year),t.month&&(o.month=t.month)),t.timeStyle&&(o.timeStyle=t.timeStyle),t.timeStyle&&t.hour12==="always"?o.hour12=!0:t.timeStyle&&t.hour12==="never"&&(o.hour12=!1),o.timeZone=Zr(r);try{return new Intl.DateTimeFormat(void 0,o).format(a)}catch{return e}},Ke=(e,t)=>e.getFieldAlias?.(t)??e.fieldsIndex?.get(t)?.alias??e.fieldsIndex?.get(t)?.name??t,He=(e,t,r,a,o)=>{if(r==null)return r;let n=e.getFieldConfiguration?.(t)?.fieldFormat;return n?.type==="number"?Yr(r,n):n?.type==="date-time"?Xr(r,n,o):Hr(r,a,o)},ea=(e,t,r,a)=>{let o=e.fieldsIndex?.get(t),n=We(t,r,e)??r;return He(e,t,n,o?.type,a)},ta=(e,t)=>Ke(e,t),Ze=(e,t,r)=>{let a=e.objectIdField,o=t.features.map(s=>s.attributes[a]),n=t.features.map(s=>{let i=s.attributes,c={};return e.fields.forEach(d=>{if(!Object.hasOwn(i,d.name))return;let u=i[d.name];if(d.name===a){c[d.name]=u;return}let m=We(d.name,u,e)??u,p=Ke(e,d.name);c[p]=He(e,d.name,m,d.type,r)}),c});return{objectIds:o,attributes:n}},ra=(e,t,r)=>{let a=e.createQuery();return a.outFields=[t],a.where=r||"1=1",a.num=1,a},aa=async(e,t,r,a)=>{let o=a.map?.allLayers.find(u=>u.id===e),n=ra(o,t,r.where),s=(await o.queryFeatures(n)).features[0],i=s?s.attributes[t]:null,c=ea(o,t,i,a.timeZone),d=ta(o,t);return{tool:"getAttribute",layerName:o.title??e,summary:`${d} = ${c}`,details:{fieldName:t,fieldAlias:d!==t?d:void 0,value:c,where:r.where}}};async function oa({layerId:e,fieldName:t,query:r},a){let{mapView:o}=L(a),n=await aa(e,t,r,o);return JSON.stringify(n,null,2)}var na=l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),fieldName:l.string().describe("The name of the field/attribute from which to get a field value."),query:l.object({where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")})}),ia=y(oa,{name:"getAttribute",description:"Returns an attribute value for a given feature.",schema:na}),ye=(e,t,r)=>r?e.hasAllFeaturesInView&&e.availableFields===t:e.hasAllFeatures&&e.availableFields===t;function ee(e,t){let r=e??"";return t!=null&&t&&(r=r?`(${r}) AND (${t})`:t),r||null}var sa=async e=>{let{targetLayer:t,fieldName:r,statisticType:a,mapView:o,layersAndFieldsRegistry:n,geometryFilter:s}=e,i=o.map?.allLayers.find(S=>S.id===t.layerId);if(!i)throw new Error(`Layer '${t.layerId}' not found.`);let c=await o.whenLayerView(i),d=n.get(t.layerId)?.fieldRegistry.get(r),u=d?.alias;if(!d)throw new Error(`Field '${r}' not found.`);let m,p;if(s){let S=await re(s,o);if("error"in S)throw new Error(S.error);if(!S.geometry)throw P(s)?new Error(`No features found matching: ${s.where}`):new Error("Failed to create geometry");if(P(s)){let E=o.map?.allLayers.find(F=>F.id===s.layerId);m={geometryLayerName:E?.title??E?.id,geometryLayerId:s.layerId,geometryWhere:s.where,distance:s.distance,units:s.units,applied:!0}}else X(s)&&(m={point:s.point,distance:s.distance,units:s.units,applied:!0});p=new De({geometry:S.geometry,distance:s.distance,units:s.units,spatialRelationship:"intersects"})}let b=ye(c,[r],!1),w=null,f=null,v=10;if(d.type!=="geometry"&&d.type!=="oid"&&d.type!=="global-id")try{let S={layer:i,useFeaturesInView:b,view:b?o:void 0,field:r,sqlWhere:ee(i.definitionExpression,t.where),...p&&{filter:p},outStatisticTypes:{include:[a]}};w=await Ve(S);let E=["string","small-integer","integer"],F=d.domain?.type==="coded-value"?d.domain:null;(E.includes(d.type)||F)&&(f=(await Pe({layer:i,useFeaturesInView:b,view:b?o:void 0,field:r,sqlWhere:ee(i.definitionExpression,t.where),...p&&{filter:p}})).uniqueValueInfos.sort((k,ot)=>ot.count-k.count).slice(0,v)),f&&d.domain?.type==="coded-value"&&(f=f.map(k=>({...k,value:F?F.getName(k.value)??k.value:k.value})))}catch(S){console.error("Statistics error:",S)}return{tool:"getStatistics",layerName:i.title??t.layerId,summary:`${a} = ${typeof w?.[a]=="number"?w[a]:"N/A"}`,details:{fieldName:r,fieldAlias:u,statisticType:a,statistic:w?.[a]??null,summaryStatistics:w,uniqueValues:f,where:t.where,spatialFilterInfo:m}}};async function la({targetLayer:e,fieldName:t,statisticType:r,geometryFilter:a},o){let n=x(o,"layersAndFieldsRegistry"),{mapView:s}=L(o),i=await sa({targetLayer:e,fieldName:t,statisticType:r,mapView:s,layersAndFieldsRegistry:n,geometryFilter:a});return JSON.stringify(i,null,2)}var ca=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),da=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),ua=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value.")}),geometryFilter:l.union([ca,da]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),fieldName:l.string().describe("The name of the field for which to get statistics. STRICTLY DO NOT use OBJECTID. Use any other field"),statisticType:l.enum(["avg","max","median","min","stddev","sum","variance","nullcount","count"]).describe("The statistic type to calculate.")}),ma=y(la,{name:"getStatistics",description:`Computes a single aggregate statistic (max, min, avg, sum, median, stddev, variance) for a numeric field across matching features. Also returns frequency analysis for categorical fields.
|
|
43
|
+
|
|
44
|
+
USE THIS TOOL FOR:
|
|
45
|
+
- "What is the average/maximum/minimum/total [field]?" \u2014 aggregate computations
|
|
46
|
+
- "Most common/frequent value of [field]?" \u2014 frequency analysis
|
|
47
|
+
- Questions requiring a mathematical aggregation across many features
|
|
48
|
+
|
|
49
|
+
DO NOT USE FOR:
|
|
50
|
+
- "How many features match X?" \u2014 use queryFeatures instead (it returns totalCount)
|
|
51
|
+
- "Show / list / find features" \u2014 use queryFeatures instead
|
|
52
|
+
- Simple counts of features matching a condition \u2014 use queryFeatures instead
|
|
53
|
+
|
|
54
|
+
Only call this tool when the answer requires computing an aggregate (avg, max, min, sum, median, stddev) over a field's values, not just counting or listing features.`,schema:ua}),pa=async(e,t,r,a,o)=>{let n=r.map?.allLayers.find(p=>p.id===e.layerId),s=await r.whenLayerView(n),i=n.title??e.layerId,c;if(a){let p=await re(a,r);if("error"in p)return{tool:"getTopFeatures",layerName:i,summary:"Geometry lookup failed",details:{error:p.error}};if(!p.geometry)return{tool:"getTopFeatures",layerName:i,summary:"No features found for geometry filter",details:{error:`No features found matching: ${"where"in a?a.where:"unknown criteria"}`}};c=p.geometry}else o&&(c=r.extent.clone());let d=t.groupByFields&&t.groupByFields.length>0,u=n.objectIdField,m=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,u])];try{let p;if(d){let f=new gt({where:e.where||"1=1",outFields:m,orderByFields:e.orderByFields,geometry:c,spatialRelationship:c?"intersects":void 0,distance:a?.distance,units:a?.units,topFilter:new yt({topCount:t.topCount,groupByFields:t.groupByFields,orderByFields:t.orderByFields})});p=await n.queryTopFeatures(f)}else{let f=n.createQuery();f.where=ee(n.definitionExpression,e.where||"1=1"),f.outFields=m.length?m:["*"],f.orderByFields=t.orderByFields,f.num=t.topCount,c&&(f.geometry=c,f.spatialRelationship="intersects"),a?.distance&&(f.distance=a.distance),a?.units&&(f.units=a.units),f.outSpatialReference=r.spatialReference;let v=ye(s,e.outFields,o??!1);try{p=v?await s.queryFeatures(f):await n.queryFeatures(f)}catch(S){console.warn("Client-side query failed, falling back to server:",S),p=await n.queryFeatures(f)}}let b=p.features.map(f=>f.attributes[u]),{attributes:w}=Ze(n,p,r.timeZone);return{tool:"getTopFeatures",layerName:i,summary:`Top ${t.topCount} features extracted`,details:{topCount:t.topCount,attributes:w,objectIds:b,objectIdField:u,where:e.where,orderByFields:t.orderByFields,...d&&{groupByFields:t.groupByFields}}}}catch(p){return{tool:"getTopFeatures",layerName:i,summary:"Query failed",details:{error:p instanceof Error?p.message:String(p)}}}},ha=async({targetLayer:e,topFilter:t,geometryFilter:r,useCurrentExtent:a},o)=>{let{mapView:n}=L(o),s=await pa(e,t,n,r,a);return JSON.stringify(s,null,2)},fa=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),ga=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),ya=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.string().describe("The SQL-92 where clause representing the feature from which to get an attribute value."),orderByFields:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.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:l.union([fa,ga]).optional().describe("Geometry filter for spatial queries. Use 'point' option with x/y coordinates from navigation results to find features at that location (point-in-polygon). Use 'layerId/where' option to filter by features from another layer."),topFilter:l.object({topCount:l.number().describe("Number of top features to return per group."),orderByFields:l.array(l.string().describe("Field(s) to rank by with ASC/DESC. Must be existing field names, not aggregate functions.")),groupByFields:l.array(l.string().describe("Field(s) to group results by. Returns top N per group."))}),useCurrentExtent:l.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).")}),wa=y(ha,{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:ya}),le=25,ba=async(e,t,r,a)=>{let o=t.map?.allLayers.find(f=>f.id===e.layerId),n=await t.whenLayerView(o),s=o.title??e.layerId,i;if(r){let f=await re(r,t);if("error"in f){let v={error:f.error};if(P(r)){let S=t.map?.allLayers.find(E=>E.id===r.layerId);v.geometryLayerName=S?.title??S?.id,v.geometryLayerId=r.layerId,v.geometryWhere=r.where}else X(r)&&(v.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"Geometry lookup failed",details:v}}if(!f.geometry){let v={};if(P(r)){let S=t.map?.allLayers.find(E=>E.id===r.layerId);v.error=`No features found matching: ${r.where}`,v.geometryLayerName=S?.title??S?.id,v.geometryLayerId=r.layerId,v.geometryWhere=r.where}else X(r)&&(v.error="Failed to create point geometry",v.point=r.point);return{tool:"queryFeatures",layerName:s,summary:"No features found for geometry filter",details:v}}i=f.geometry}else a&&(i=t.extent.clone());let c=ye(n,e.outFields,a??!1),d=o.objectIdField,u=o.createQuery();u.where=ee(o.definitionExpression,e.where||"1=1"),u.outFields=e.outFields.includes("*")?["*"]:[...new Set([...e.outFields,d])],u.orderByFields=e.orderByFields,i&&(u.geometry=i,u.spatialRelationship="intersects"),r?.distance&&(u.distance=r.distance),r?.units&&(u.units=r.units),u.outSpatialReference=t.spatialReference;let m,p;try{m=c?await n.queryFeatureCount(u):await o.queryFeatureCount(u),m>0&&m<=le&&(p=c?await n.queryFeatures(u):await o.queryFeatures(u))}catch(f){console.warn("Client-side query failed, falling back to server:",f),m=await o.queryFeatureCount(u),m>0&&m<=le&&(p=await o.queryFeatures(u))}let{objectIds:b,attributes:w}=p?Ze(o,p,t.timeZone):{objectIds:void 0,attributes:void 0};return{tool:"queryFeatures",layerName:s,summary:`${m} features found`,details:{totalCount:m,where:e.where,orderByFields:e.orderByFields,outFields:e.outFields,...b&&{objectIds:b,objectIdField:d},...w&&{attributes:w},...m>le&&{note:`${m} features found.`}}}};async function va({targetLayer:e,geometryFilter:t,useCurrentExtent:r},a){let{mapView:o}=L(a),n=await ba(e,o,t,r);return JSON.stringify(n,null,2)}var Sa=l.object({layerId:l.string().describe("The layerId of the layer containing the geometry by which to filter."),where:l.string().describe("The SQL-92 where clause representing the features from which to filter."),distance:l.number().optional().describe("The buffer distance around the geometry."),units:z.optional().describe("The units for the distance buffer.")}),xa=l.object({point:l.object({x:l.number().describe("X coordinate (longitude) from navigation result"),y:l.number().describe("Y coordinate (latitude) from navigation result"),spatialReference:l.object({wkid:l.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:l.number().optional().describe("Optional buffer distance around the point."),units:z.optional().describe("The units for the distance buffer.")}),Ta=l.object({targetLayer:l.object({layerId:l.string().describe("The layerId of the layer containing the field from which to get a value."),where:l.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:l.array(l.string().describe("The field(s) and order for which to sort the resulting features.")),outFields:l.array(l.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:l.union([Sa,xa]).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:l.boolean().optional().describe("Set to true ONLY when user explicitly asks about features 'in my view', 'on my map', 'I am looking at', OR when the user refers back to features previously identified using the current extent (e.g. 'these', 'those', 'them', 'the same ones'). Default is false (queries entire layer).")}),Ea=y(va,{name:"queryFeatures",description:`Queries features from a layer. Returns the total count of matching features, plus individual feature attributes if \u226425 features match.
|
|
55
|
+
|
|
56
|
+
USE THIS TOOL FOR:
|
|
57
|
+
- "Show / display / list features where..." \u2014 finding and listing features
|
|
58
|
+
- "How many X are Y?" \u2014 counting features that match a condition
|
|
59
|
+
- "Which features..." / "Find features..." \u2014 identifying specific features
|
|
60
|
+
- Spatial queries \u2014 finding features near/within/intersecting other features
|
|
61
|
+
- Any question where the user wants to SEE or COUNT matching features
|
|
62
|
+
|
|
63
|
+
This is the DEFAULT tool for most queries. When in doubt, use this tool.`,schema:Ta}),Je=[ia,ma,wa,Ea],Ye=[Ur,jr,Rr],Ia=async(e,t)=>{await h({text:"Requesting LLM for layer filter results"},t);let r=await R("data_explore_filter_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer filter tools");let{userTimezone:a,userTimezoneOffset:o}=Ue(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await j({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:Ye}),i=[...e.dataExplorationMessages,s];if(!((s.tool_calls?.length??0)>0))return await h({text:"LLM determined no filter changes needed"},t),{...e,dataExplorationMessages:i};let c=[...i,s],d=s.content.toString();return await ge(s,t),{...e,dataExplorationMessages:c,outputMessage:d}},ka=async(e,t)=>{await h({text:"Requesting LLM for layer query results"},t);let r=await R("data_explore_query_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let{userTimezone:a,userTimezoneOffset:o}=Ue(),n={layerFieldInfo:e.layerFieldInfo,userTimezone:a,userTimezoneOffset:o,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},s=await j({promptText:r,modelTier:"advanced",messages:e.dataExplorationMessages,inputVariables:n,tools:Je}),i=s.content.toString();return await ge(s,t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,s],outputMessage:i,status:"success",summary:i?U(i):"Query executed."}},$a=async(e,t)=>{try{await h({text:"Requesting LLM for summary on query results"},t);let r=await R("summarize_query_response_prompt"),a={queryResponse:e.queryResponse,assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps},o=await Ee({promptText:r,modelTier:"fast",messages:e.dataExplorationMessages,inputVariables:a}),n=typeof o=="string"?o:o.content,s=new ne(n);await h({text:`Received response from LLM: ${n}`},t);let i=n;return{...e,outputMessage:i,status:"success",summary:i?U(i):"Summary generated.",dataExplorationMessages:[...e.dataExplorationMessages,s]}}catch(r){throw await h({text:"Error during filter LLM request"},t),new Error(`Error during filter LLM request: ${r instanceof Error?r.message:String(r)}`)}};async function _a(e,t){let r=await new q(Ye).invoke({messages:e.dataExplorationMessages},t);return await h({text:`Finished executing layer filter tool: ${r.messages.map(a=>a.content).join(", ")}`},t),{...e}}var Ca=new q(Je);async function Na(e,t){let{messages:r}=await Ca.invoke({messages:e.dataExplorationMessages},t),a=[],o=[];for(let n of r){let s=n.content,i;typeof s!="string"&&(i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Skipping non-string tool output:",raw:s}});try{typeof s=="string"?i=JSON.parse(s):i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:"Invalid tool output type",raw:s}}}catch{i={tool:n.name??"unknown",layerName:"unknown",summary:"Query failed",details:{error:s}}}a.push(i),i.details&&typeof i.details=="object"&&"error"in i.details?o.push(`- ${i.tool}: Error - ${String(i.details.error)}`):o.push(`- ${i.layerName}: ${i.summary}`)}return await h({text:`Finished executing layer query tool: ${o.join(", ")}`},t),{...e,dataExplorationMessages:[...e.dataExplorationMessages,...r],queryResponse:a,status:"success",outputMessage:o.join(`
|
|
64
|
+
`),summary:o.length>0?U(o.join(`
|
|
65
|
+
`)):"Query executed."}}var Fa=10,Ma=["string","small-integer","integer"],Aa=async(e,t,{includeSummaryStatistics:r=!0,includeUniqueValues:a=!0}={})=>{let o=null,n=null;try{if(t.type!=="geometry"&&t.type!=="oid"&&t.type!=="global-id"){r&&(o=await Ve({layer:e,field:t.name}));let s=t.domain?.type==="coded-value"?t.domain:null;a&&(Ma.includes(t.type)||s)&&(n=(await Pe({layer:e,field:t.name})).uniqueValueInfos.sort((i,c)=>c.count-i.count).slice(0,Fa),s&&(n=n.map(i=>({...i,value:s.getName(i.value)??i.value}))))}}catch(s){console.error(`Error fetching statistics for field ${t.name}:`,s)}return{summaryStatistics:o,uniqueValues:n}};function qa(e,t){return["string","small-integer","integer"].includes(e)||t==="coded-value"}async function Ra(e,t,r,a=!0){let o=[],n=[];for(let s of e){let i=function(b){let w=t.get(b)?.layerItem;return w?[w.name&&`Name: ${w.name}`,w.title&&`Title: ${w.title}`,w.description&&`Description: ${w.description}`].filter(Boolean).join(" | "):b},{layerId:c,results:d}=s,u=r.map?.allLayers.find(b=>b.id===c),m=t.get(c)?.fieldRegistry;if(!m)continue;let p=o.find(b=>b.layerId===c);p||(p={layerId:c,layerSummary:i(c),fieldInfos:[]},o.push(p));for(let b of d){let w=m.get(b.name);if(!w)continue;let f=w.statistics,v=a&&!f?.summaryStatistics,S=qa(w.type,w.domain?.type)&&!f?.uniqueValues;if(v||S){let E=Aa(u,w,{includeSummaryStatistics:v,includeUniqueValues:S}).then(F=>{let k={summaryStatistics:f?.summaryStatistics??null,uniqueValues:f?.uniqueValues??null};v&&(k.summaryStatistics=F.summaryStatistics),S&&(k.uniqueValues=F.uniqueValues),m.set(w.name,{...w,statistics:k}),w.statistics=k});n.push(E)}p.fieldInfos.push(w)}}return await Promise.all(n),{layerFieldInfo:o,didFetchStatistics:n.length>0}}var qe=/\b(average|avg|mean|median|max(?:imum)?|min(?:imum)?|sum|total|count|std(?:dev|\s*deviation)|variance|null\s*count|missing\s*values?|range)\b/iu;function La(e,t){return qe.test(e)||qe.test(t)}var za=async(e,t)=>{try{await h({text:"Preparing field information for vector search results"},t);let r=x(t,"layersAndFieldsRegistry"),{mapView:a}=L(t),{assignedTask:o,userRequest:n}=e.agentExecutionContext,s=La(o,n),{layerFieldInfo:i,didFetchStatistics:c}=await Ra(e.vectorSearchFieldResults,r,a,s);return c?await h({text:"Statistics fetched"},t):await h({text:"Statistics skipped"},t),await h({text:"Field information prepared"},t),{...e,layerFieldInfo:i}}catch(r){throw await h({text:"Error during fetching statistics"},t),new Error(`Error during fetching statistics: ${r instanceof Error?r.message:String(r)}`)}},Re=.7,ja=10,Da=async(e,t)=>{try{await h({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Re,topResults:ja,embeddingCache:o}),s=n.map(({layerId:c,results:d})=>{let u=d.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
|
|
66
|
+
`);return`${a.get(c)?.layerItem.name??c}:
|
|
67
|
+
${u}`}).join(`
|
|
68
|
+
`),i;return n.length>0?i=`Vector search completed. Matching layers and fields with scores:
|
|
69
|
+
${s}`:i=`No vector search results found for score over ${Re}.`,await h({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await h({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Oa=.7,Va=async(e,t)=>{try{await h({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Oa,embeddingCache:o}),s=n.map(d=>d.id),i=n.map(({id:d,score:u})=>`${a.get(d)?.layerItem.name??d} (${u.toFixed(2)})`).join(`
|
|
70
|
+
`),c;return s.length>0?c=`Vector search completed. Matching layers with scores:
|
|
71
|
+
${i}`:c="Vector search completed. No matching layers found.",await h({text:c},t),{...e,vectorSearchLayerIds:s}}catch(r){throw await h({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Pa=(e,t)=>te(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Data Exploration Agent")(e,t),Ga=()=>new A(Qe).addNode("requireDataExplorationServices",Pa).addNode("vectorSearchLayers",Va).addNode("vectorSearchFields",Da).addNode("fieldStatistics",za).addNode("queryAgent",ka).addNode("queryTools",Na).addNode("summarizeQueryResponseLLM",$a).addNode("filterAgent",Ia).addNode("filterTools",_a).addNode("earlyExit",Fr).addEdge(M,"requireDataExplorationServices").addEdge("requireDataExplorationServices","vectorSearchLayers").addConditionalEdges("vectorSearchLayers",e=>e.vectorSearchLayerIds.length?"vectorSearchFields":"earlyExit").addConditionalEdges("vectorSearchFields",e=>e.vectorSearchFieldResults.length?"fieldStatistics":"earlyExit").addEdge("fieldStatistics","queryAgent").addConditionalEdges("queryAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"queryTools":"filterAgent").addConditionalEdges("queryTools",e=>e.queryResponse.length?"summarizeQueryResponseLLM":"filterAgent").addEdge("summarizeQueryResponseLLM","filterAgent").addConditionalEdges("filterAgent",e=>(e.dataExplorationMessages[e.dataExplorationMessages.length-1]?.tool_calls?.length??0)>0?"filterTools":T).addEdge("filterTools",T).addEdge("earlyExit",T),Ba=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).
|
|
72
|
+
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.
|
|
73
|
+
_Example: “Only show stations where Brand is Shell”_
|
|
74
|
+
_Example: “Make Shell stations stand out on the map”_
|
|
75
|
+
_Example: “Gray out all stations that aren’t Shell”_
|
|
76
|
+
This also includes questions that ask which feature meets a given condition or where a particular feature in the data is located (e.g., “Where is the spring with the highest elevation?”). However, this agent does not handle addresses.
|
|
77
|
+
_Example: “How many features are there?”_
|
|
78
|
+
_Example: “What’s the average population?”_
|
|
79
|
+
_Example: “Which values are in the status field?”_`,Vs={id:"dataExploration",name:"Data Exploration Agent",description:Ba,createGraph:Ga,workspace:Qe},Le=.7,Qa=10,Ua=async(e,t)=>{try{await h({text:"Similarity search to find fields"},t);let r=x(t,"fieldSearch"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"embeddingCache"),n=await r.searchFields({text:e.agentExecutionContext.assignedTask,layerIds:e.vectorSearchLayerIds,minScore:Le,topResults:Qa,embeddingCache:o}),s=n.map(({layerId:c,results:d})=>{let u=d.map(m=>` - ${m.name} (${m.score.toFixed(2)})`).join(`
|
|
80
|
+
`);return`${a.get(c)?.layerItem.name??c}:
|
|
81
|
+
${u}`}).join(`
|
|
82
|
+
`),i;return n.length>0?i=`Vector search completed. Matching layers and fields with scores:
|
|
83
|
+
${s}`:i=`No vector search results found for score over ${Le}.`,await h({text:i},t),{...e,vectorSearchFieldResults:n}}catch(r){throw await h({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}},Wa=.7,Ka=async(e,t)=>{try{await h({text:`Similarity search to find layers: ${e.agentExecutionContext.assignedTask}`},t);let r=x(t,"layerSearch"),a=x(t,"layersAndFieldsRegistry"),o=await r.searchLayers({text:e.agentExecutionContext.assignedTask,minScore:Wa}),n=o.map(c=>c.id),s=o.map(({id:c,score:d})=>`${a.get(c)?.layerItem.name??c} (${d.toFixed(2)})`).join(`
|
|
84
|
+
`),i;return n.length>0?i=`Vector search completed. Matching layers with scores:
|
|
85
|
+
${s}`:i="Vector search completed. No matching layers found.",await h({text:i},t),{...e,vectorSearchLayerIds:n}}catch(r){throw await h({text:`Error during vector search: ${r instanceof Error?r.message:String(r)}`},t),new Error(`Vector search failed: ${r instanceof Error?r.message:String(r)}`)}};async function Ha(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n?s=bt({basemapTheme:await Ce(a),geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,8)})[0]:s=vt({basemapTheme:await Ce(a),geometryType:r.geometryType,numColors:Math.min(t.length,8)}).primaryScheme,{layer:r,view:a,attributes:t.map(i=>({field:i,label:r.fields.find(c=>c.name===i)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),pieChartScheme:s}}async function Za(e){return await wt(e)}async function Ja({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:n?"chart-size":"chart",fields:a,layer:i,view:s,colorSchemeTags:o};try{let d=await Ha(c),u=await Za(d);return i.renderer=u.renderer,i.visible=!0,`Chart renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying chart renderer: ${d instanceof Error?d.message:String(d)}`}}var Ya=["mapView"];function C(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("LayerStylingAgent context missing");let r=Ya.filter(a=>!(a in t));if(r.length)throw new Error(`LayerStylingAgent context missing: ${r.join(", ")}`);return t}async function Xa({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Ja({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var eo=l.object({layerId:l.string().describe("The id of the layer to apply the chart renderer to"),fields:l.array(l.string()).describe("The fields to use for the chart renderer (multiple numeric fields)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to vary the chart size (chart-size)")}),to=y(Xa,{name:"chart",description:`Label: Charts
|
|
86
|
+
Description: Show the values of two or more categories as a proportion of the total using a pie chart.
|
|
87
|
+
Keywords: pie, chart, all categories, breakdown, proportion
|
|
88
|
+
Example: Show the total number of homes built in each decade using a pie chart for each feature.
|
|
89
|
+
Fields: This style requires 2-8 number fields.
|
|
90
|
+
|
|
91
|
+
Label: Charts and Size
|
|
92
|
+
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.
|
|
93
|
+
Keywords: pie, chart, all categories, breakdown, proportion, total, amount, how much, sum, graduated size, proportional size
|
|
94
|
+
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.
|
|
95
|
+
Fields: This style requires 2-8 number fields.`,schema:eo});function ro(e){let{fields:t,layer:r,view:a,theme:o,colorSchemeTags:n}=e,s=t[0],i;return n&&(i=he({geometryType:r.geometryType,includedTags:n,theme:o||"high-to-low"})[0]),{layer:r,view:a,startTime:s,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:i}}async function ao(e){return await St(e)}async function oo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"color-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let d=ro(c),u=await ao(d);return i.renderer=u.renderer,i.visible=!0,`Color-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function no({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await oo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var io=l.object({layerId:l.string().describe("The id of the layer to apply the color-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color-age renderer (temporal/date data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),so=y(no,{name:"color-age",description:`Label: Age (color)
|
|
96
|
+
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.
|
|
97
|
+
Keywords: since, age, how old, how long
|
|
98
|
+
Example: Show the age of each feature based on its reported date.
|
|
99
|
+
Fields: This style requires at least one field with a date type.`,schema:io});function lo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,{theme:n}=e,s=t[1],i=t[0],c;return o&&(c=he({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:i,normalizationField:s,theme:n,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0,colorScheme:c}}async function co(e){return await xt(e)}async function uo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"color",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let d=lo(c),u=await co(d);return i.renderer=u.renderer,i.visible=!0,`Color renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color renderer: ${d instanceof Error?d.message:String(d)}`}}async function mo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await uo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var po=l.object({layerId:l.string().describe("The id of the layer to apply the color renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the color renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color ramp")}),ho=y(mo,{name:"color",description:`Label: Counts and Amounts (color)
|
|
100
|
+
Description: Vary color along a continuous color ramp to represent numeric or ranked data.
|
|
101
|
+
Keywords: graduated color, choropleth, continuous color, hue, color, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease
|
|
102
|
+
Example: Color each feature based on the population density.
|
|
103
|
+
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:po});function fo(e){let{fields:t,layer:r,view:a,colorSchemeTags:o,theme:n}=e,s,i,c=t[0];return o&&(i=he({geometryType:r.geometryType,includedTags:o,theme:n||"high-to-low"})[0]),{layer:r,view:a,field:c,normalizationField:s,theme:n,colorOptions:{colorScheme:i}}}async function go(e){return await Tt(e)}async function yo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"color-size-univariate",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let d=fo(c),u=await go(d);return i.renderer=u.renderer,i.visible=!0,`Color-size-univariate renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying color-size-univariate renderer: ${d instanceof Error?d.message:String(d)}`}}async function wo({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await yo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var bo=l.object({layerId:l.string().describe("The id of the layer to apply the color-size univariate renderer to"),fields:l.array(l.string()).describe("The fields to use for the color-size univariate renderer"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color and size ramps")}),vo=y(wo,{name:"color-size-univariate",description:`Label: Color and Size (univariate)
|
|
104
|
+
Description: Vary symbol size and color based on the values of two numeric attributes.
|
|
105
|
+
Keywords: continuous color, hue, color, size, gradation, saturation, lightness, percent, rate, ratio, index, how much, increase, decrease, amount
|
|
106
|
+
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.
|
|
107
|
+
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:bo});function So(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n;return o&&(n=It({includedTags:o,numColors:Math.min(t.length,8)})[0]),{layer:r,view:a,legendOptions:{unit:"units"},attributes:t.map(s=>({field:s,label:r.fields.find(i=>i.name===s)?.alias??""})).slice(0,8),outlineOptimizationEnabled:!0,dotDensityScheme:n}}async function xo(e){return await Et(e)}async function To({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"dot-density",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=So(i),d=await xo(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 Eo({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=C(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await To({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Io=l.object({layerId:l.string().describe("The id of the layer to apply the dot density renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the dot density renderer (population or count data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),ko=y(Eo,{name:"dot-density",description:`Dot Density
|
|
108
|
+
Use dot density to visualize the distribution of one attribute or compare the density of multiple attributes. This is only valid for polygon layers.
|
|
109
|
+
**Use cases:**
|
|
110
|
+
- Population distribution visualization
|
|
111
|
+
- Comparing multiple categories within areas
|
|
112
|
+
- Showing spatial distribution patterns
|
|
113
|
+
**Examples:**
|
|
114
|
+
- Show the density of the population based on various race/ethnic groups
|
|
115
|
+
- Visualize distribution of different crops across regions
|
|
116
|
+
- Display demographic patterns within census tracts
|
|
117
|
+
**Fields:** Requires 2-8 number fields.
|
|
118
|
+
**Keywords:** density, how much, how many, total, number, amount`,schema:Io});function $o(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s=t[0];return o&&(n=$t({includedTags:o,basemap:a.map?.basemap||"topo"})[0]),{layer:r,view:a,field:s,heatmapScheme:n}}async function _o(e){return await kt(e)}async function Co({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"heatmap",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=$o(i),d=await _o(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 No({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=C(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Co({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Fo=l.object({layerId:l.string().describe("The id of the layer to apply the heatmap renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the heatmap renderer (typically point density)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Mo=y(No,{name:"heatmap",description:`Label: Heat Map
|
|
119
|
+
Description: Show areas of high density with colors that appear to glow hotter. This is only valid for point layers.
|
|
120
|
+
Keywords: density, heatmap, hot spots, pattern, cluster
|
|
121
|
+
Example: Create a heatmap
|
|
122
|
+
Fields: This typically requires zero or one field of type number.`,schema:Fo});function Ao(e){let{fields:t,layer:r,view:a,styleName:o,colorSchemeTags:n}=e,s;return n&&(s=Ct({geometryType:r.geometryType,includedTags:n,numColors:Math.min(t.length,10)})[0]),{layer:r,view:a,fields:t.map(i=>({name:i})).slice(0,9),outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,includeSizeVariable:o.includes("Size"),predominanceScheme:s}}async function qo(e){return await _t(e)}async function Ro({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,includeSize:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:n?"predominance-size":"predominance",fields:a,layer:i,view:s,colorSchemeTags:o};try{let d=Ao(c),u=await qo(d);return i.renderer=u.renderer,i.visible=!0,`Predominance renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying predominance renderer: ${d instanceof Error?d.message:String(d)}`}}async function Lo({layerId:e,fields:t,colorSchemes:r,includeSize:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Ro({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,includeSize:a})}var zo=l.object({layerId:l.string().describe("The id of the layer to apply the predominance renderer to"),fields:l.array(l.string()).describe("The fields to use for the predominance renderer (competing categories)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),includeSize:l.boolean().optional().describe("Whether to include size visualization (predominance-size)")}),jo=y(Lo,{name:"predominance",description:`Label: Predominant category
|
|
123
|
+
Description: Compare attributes that share a common subject and unit of measurement to see which has the highest value.
|
|
124
|
+
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top
|
|
125
|
+
Example: Using fields for Corn Acres, Wheat Acres, and Cotton Acres, show the predominant crop harvested in each area.
|
|
126
|
+
Fields: This style relies on 2-10 number fields.
|
|
127
|
+
|
|
128
|
+
Label: Predominant category and Size
|
|
129
|
+
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.
|
|
130
|
+
Keywords: predominant, winner, won, competing, most, most common, most frequent, dominant, prevalent, top, amount, total, how much, proportional size, graduated size, sum
|
|
131
|
+
Example: Show the predominant crop in each area and vary the size of each symbol based on the total of all categories.
|
|
132
|
+
Fields: This style relies on 2-10 number fields.`,schema:zo});function Do(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n,s={field:t[0]},i={field:t[1]};return o&&(n=Ft({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field1:s,field2:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,relationshipScheme:n}}async function Oo(e){return await Nt(e)}async function Vo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o}){let n=t,s=e?.allLayers.find(c=>c.id===r);if(!s)return`Could not find layer for id: ${r}`;let i={styleName:"relationship",fields:a,layer:s,view:n,colorSchemeTags:o};try{let c=Do(i),d=await Oo(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 Po({layerId:e,fields:t,colorSchemes:r},a){let{mapView:o}=C(a);return await I({type:"show-legend",data:{layerIds:[e]}},a),await Vo({arcgisMap:o.map,arcgisMapView:o,layerId:e,fields:t,colorSchemes:r})}var Go=l.object({layerId:l.string().describe("The id of the layer to apply the relationship renderer to"),fields:l.array(l.string()).describe("The two fields to use for the relationship renderer (bivariate visualization)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use")}),Bo=y(Po,{name:"relationship",description:`Label: Relationship
|
|
133
|
+
Description: Overlays two color ramps to represent the relationship between two numeric attributes.
|
|
134
|
+
Keywords: relationship, correlation, compare, related, bivariate choropleth, bivariate color
|
|
135
|
+
Example: Show the relationship between tree height and carbon storage
|
|
136
|
+
Fields: This style requires two number fields.`,schema:Go});function Qo(e){let{fields:t,layer:r,view:a,theme:o}=e,n=t[0];return{layer:r,view:a,startTime:n,endTime:new Date,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Uo(e){return await Mt(e)}async function Wo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"size-age",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let d=Qo(c),u=await Uo(d);return i.renderer=u.renderer,i.visible=!0,`Size-age renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size-age renderer: ${d instanceof Error?d.message:String(d)}`}}async function Ko({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Wo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var Ho=l.object({layerId:l.string().describe("The id of the layer to apply the size-age renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size-age renderer (temporal data with size)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),Zo=y(Ko,{name:"size-age",description:`Label: Age (size)
|
|
137
|
+
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.
|
|
138
|
+
Keywords: since, age, how old, how long
|
|
139
|
+
Example: Change the size of features so older features are larger than new features.
|
|
140
|
+
Fields: This style requires at least one field with a date type.`,schema:Ho});function Jo(e){let{fields:t,layer:r,view:a}=e,{theme:o}=e,n=t[1],s=t[0];return{layer:r,view:a,field:s,normalizationField:n,theme:o,sizeOptimizationEnabled:!0,outlineOptimizationEnabled:!0}}async function Yo(e){return await At(e)}async function Xo({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"size",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let d=Jo(c),u=await Yo(d);return i.renderer=u.renderer,i.visible=!0,`Size renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying size renderer: ${d instanceof Error?d.message:String(d)}`}}async function en({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await Xo({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var tn=l.object({layerId:l.string().describe("The id of the layer to apply the size renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the size renderer (numeric data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the size ramp")}),rn=y(en,{name:"size",description:`Label: Counts and Amounts (size)
|
|
141
|
+
Description: Vary symbol sizes along a continuous ramp to represent numeric or ranked data.
|
|
142
|
+
Keywords: graduated size, proportional size, how much, total, number, amount, size
|
|
143
|
+
Example: Vary the size of each point based on the total population.
|
|
144
|
+
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.
|
|
145
|
+
|
|
146
|
+
Label: Continuous Timeline (size)
|
|
147
|
+
Description: Vary symbol sizes along a continuous ramp to represent dates.
|
|
148
|
+
Keywords: graduated size, proportional size, classed size, how much, total, number, when
|
|
149
|
+
Example: Vary the size of each feature based on the date a ticket was completed.
|
|
150
|
+
Fields: This style requires a single field with a date type.`,schema:tn});function an(e){let{fields:t,layer:r,view:a,colorSchemeTags:o}=e,n=t[0],s=t[1],i=t[2],c;return o&&(c=Rt({geometryType:r.geometryType,includedTags:o})[0]),{layer:r,view:a,field:n,field2:s,field3:i,outlineOptimizationEnabled:!0,sizeOptimizationEnabled:!0,typeScheme:c}}async function on(e){return await qt(e)}async function nn({arcgisMap:e,arcgisMapView:t,layerId:r,fields:a,colorSchemes:o,theme:n}){let s=t,i=e?.allLayers.find(d=>d.id===r);if(!i)return`Could not find layer for id: ${r}`;let c={styleName:"type",fields:a,layer:i,view:s,colorSchemeTags:o,theme:n};try{let d=an(c),u=await on(d);return i.renderer=u.renderer,i.visible=!0,`Type renderer applied to layer: ${i.title??i.id} using fields ${a.join(", ")}`}catch(d){return`Error applying type renderer: ${d instanceof Error?d.message:String(d)}`}}async function sn({layerId:e,fields:t,colorSchemes:r,theme:a},o){let{mapView:n}=C(o);return await I({type:"show-legend",data:{layerIds:[e]}},o),await nn({arcgisMap:n.map,arcgisMapView:n,layerId:e,fields:t,colorSchemes:r,theme:a})}var ln=l.object({layerId:l.string().describe("The id of the layer to apply the type renderer to"),fields:l.array(l.string()).describe("The field(s) to use for the type renderer (categorical data)"),colorSchemes:l.array(l.string()).optional().describe("Optional color scheme tags to use"),theme:l.enum(["above-and-below","above","below","centered-on","extremes","high-to-low"]).optional().describe("Optional theme for the color scheme")}),cn=y(sn,{name:"type",description:`Label: Types (unique symbols)
|
|
151
|
+
Description: Represent features as categories with different symbol colors or shapes. Examples include type of tree, road class, or province name.
|
|
152
|
+
Keywords: categorical, category, type, unique, discrete, point of interest, region, group
|
|
153
|
+
Example: Color each feature based on the region it belongs to
|
|
154
|
+
Fields: This style requires a single field which may be a string, number, or date type. It is usually a string.`,schema:ln}),Xe=[to,so,ho,vo,ko,Mo,jo,Bo,Zo,rn,cn],et=(e,t=3)=>{let r=e.map((o,n)=>o.type==="human"?n:-1).filter(o=>o!==-1);if(r.length===0)return[];let a=r.length>t?r[r.length-t]:r[0];return e.slice(a)},dn=async(e,t)=>{await h({text:"Requesting LLM for layer query results"},t);let r=await R("navigation_intent_prompt");if(!t?.configurable)throw new Error("config.configurable is required for layer query tools");let a={layerFieldInfo:e.layerFieldInfo},o=await j({promptText:r,modelTier:"advanced",messages:et(e.agentExecutionContext.messages),inputVariables:a,tools:Xe});return await ge(o,t),{...e,agentExecutionContext:{...e.agentExecutionContext,messages:[...e.agentExecutionContext.messages,o]}}};async function un(e,t){let r=await new q(Xe).invoke({messages:et(e.agentExecutionContext.messages)},t),a=r.messages.map(n=>n.text).join(`
|
|
155
|
+
`);await h({text:`Finished executing layer filter tool: ${a}`},t);let o=r.messages.map(n=>n.text).join(`
|
|
156
|
+
`);return{...e,outputMessage:o}}var tt=g.Root({agentExecutionContext:g({reducer:B,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:g({reducer:Q,default:()=>""}),vectorSearchLayerIds:g(),vectorSearchFieldResults:g(),layerFieldInfo:g(),selectedLayerId:g()}),mn=async(e,t)=>(await h({text:"Exiting Layer Styling agent"},t),e),pn=async(e,t)=>{try{await h({text:"Populating layer and field info"},t);let r=[];for(let a of e.vectorSearchFieldResults){let o=function(u){let m=i.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:n,results:s}=a,i=x(t,"layersAndFieldsRegistry"),c=i.get(n)?.fieldRegistry;if(!c)continue;let d=r.find(u=>u.layerId===n);d||(d={layerId:n,layerSummary:o(n),fieldInfos:[]},r.push(d));for(let u of s){let m=c.get(u.name);m&&d.fieldInfos.push(m)}}return await h({text:"Populated layerFieldInfo"},t),{...e,layerFieldInfo:r}}catch(r){throw await h({text:"Error populating layerFieldInfo"},t),new Error(`Error populating layerFieldInfo: ${r instanceof Error?r.message:String(r)}`)}},hn=(e,t)=>{let r=e.vectorSearchLayerIds??[];if(r.length<=1)return{...e,selectedLayerId:e.vectorSearchLayerIds[0]};let{hitlResponse:a}=t.configurable;if(!a||a.agentId!==ze.id||a.id!=="reviewLayerSelection"){let n={agentId:ze.id,id:"reviewLayerSelection",kind:"singleSelection",message:"Choose a layer to apply the styles.",metadata:[...r]};throw new Se(n)}let o=null;return Array.isArray(a.payload)&&a.payload.length>0&&(o=a.payload[0]),{...e,selectedLayerId:o??e.vectorSearchLayerIds[0]}},fn=(e,t)=>te(["layerSearch","fieldSearch","layersAndFieldsRegistry"],"Layer Styling Agent")(e,t),gn=()=>new A(tt).addNode("requireLayerStylingServices",fn).addNode("vectorSearchLayers",Ka).addNode("layerSelectionHITL",hn).addNode("vectorSearchFields",Ua).addNode("populateLayerFieldInfo",pn).addNode("agent",dn).addNode("tools",un).addNode("earlyExit",mn).addEdge(M,"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",T).addEdge("earlyExit",T),yn=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.
|
|
157
|
+
_Example: “Color points by sales amount”_
|
|
158
|
+
_Example: “Show population density with a color gradient”_
|
|
159
|
+
_Example: “Create a relationship map between height and depth”_
|
|
160
|
+
_Example: “Vary circle sizes according to population”_`,ze={id:"layerStyling",name:"Layer Styling Agent",description:yn,createGraph:gn,workspace:tt},rt=g.Root({agentExecutionContext:g({reducer:B,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:g({reducer:Q,default:()=>""}),summary:g({reducer:$,default:()=>""}),status:g({reducer:$}),helpInternalState:g({reducer:$,default:()=>({toolCallMessage:void 0})})}),wn=(e,t)=>{let r=Array.from(e.values()).find(({layerItem:n})=>n.title?.toLowerCase().includes(t.toLowerCase()));if(!r){let n=Array.from(e.values()).map(s=>s.layerItem.title).join(", ");return`Could not find a layer matching "${t}". Available layers: ${n}`}let a=Array.from(r.fieldRegistry.values()),o=a.map(n=>`- **${n.alias||n.name}** (\`${n.name}\`, ${n.type})${n.description?`: ${n.description}`:""}`).join(`
|
|
161
|
+
`);return`**${r.layerItem.title}** has ${a.length} field(s):
|
|
162
|
+
|
|
163
|
+
${o}`},bn=async({layerTitle:e},t)=>{let r=x(t,"layersAndFieldsRegistry");return wn(r,e)},vn=y(bn,{name:"listLayerFields",description:"Lists all fields for a given layer by title. Use when the user asks to see fields, columns, or attributes of a specific layer.",schema:l.object({layerTitle:l.string().describe("The title or partial title of the layer to list fields for.")})}),at=[vn],Sn=e=>{if(!e||e.size===0)return"No layers available in this map.";let t=Array.from(e.values()).map(({layerItem:r,fieldRegistry:a},o)=>{let n=Array.from(a.values()).map(i=>i.name).slice(0,10).join(", "),s=a.size>10?` (and ${a.size-10} more)`:"";return`${o+1}. "${r.title}". Description: ${r.description}
|
|
164
|
+
Fields: ${n}${s}`}).join(`
|
|
165
|
+
|
|
166
|
+
`);return`This map contains ${e.size} layer(s):
|
|
167
|
+
|
|
168
|
+
${t}`},xn=e=>{let t=e?.list()??[];return t.length?t.map(r=>`- ${r.agent.name}: ${r.agent.description}`).join(`
|
|
169
|
+
`):"No agents currently available."};async function Tn(e,t){let r=await R("help_prompt"),a=x(t,"layersAndFieldsRegistry"),o=x(t,"agentRegistry");try{let n=await j({promptText:r,modelTier:"fast",tools:at,inputVariables:{layerSummary:Sn(a),agents:xn(o),assignedTask:e.agentExecutionContext.assignedTask,userRequest:e.agentExecutionContext.userRequest,priorSteps:e.agentExecutionContext.priorSteps}}),s=(n.tool_calls?.length??0)>0,i=typeof n.text=="string"?n.text.trim():"";return{...e,helpInternalState:{...e.helpInternalState,toolCallMessage:s?n:void 0},outputMessage:s?e.outputMessage:i,summary:s?"Prepared help tool call from assigned task.":"Provided map-related help based on the assigned task.",status:s?e.status:"success"}}catch(n){let s=n instanceof Error?n.message:String(n);return{...e,outputMessage:`Error invoking help agent: ${s}`,summary:"Help agent execution failed.",status:"failed"}}}var En=(e,t)=>te(["agentRegistry"],"Help Agent")(e,t);async function In(e,t){let r=new q(at);try{let a=e.helpInternalState.toolCallMessage;if(!a)throw new Error("helpToolCalling: missing helpInternalState.toolCallMessage");let o=(await r.invoke({messages:[a]},t)).messages.map(n=>n.text).join(`
|
|
170
|
+
`);return await h({text:`Finished executing help tool: ${o}`},t),{...e,outputMessage:o,status:"success",summary:o?U(o):"Help executed.",helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}catch(a){let o=a instanceof Error?a.message:String(a);return await h({text:`Help tool execution failed: ${o}`},t),{...e,outputMessage:`Help tool execution failed: ${o}`,status:"failed",summary:`Help tool execution failed: ${o}`,helpInternalState:{...e.helpInternalState,toolCallMessage:void 0}}}}var kn=()=>new A(rt).addNode("requireHelpServices",En).addNode("agent",Tn).addNode("tools",In).addEdge(M,"requireHelpServices").addEdge("requireHelpServices","agent").addConditionalEdges("agent",e=>e.helpInternalState.toolCallMessage?"tools":T).addEdge("tools",T),$n=String.raw`- **help** — Enables users to ask questions about the map, layers, fields, and it's capabilities.
|
|
171
|
+
|
|
172
|
+
_Example: “Tell me about this map”_
|
|
173
|
+
_Example: “List all layers in this map”_
|
|
174
|
+
_Example: “List fields in protected areas layer”_
|
|
175
|
+
_Example: “What agents are available to me?”_
|
|
176
|
+
_Example: “What can you do?”_
|
|
177
|
+
_Example: “What can I ask”_
|
|
178
|
+
|
|
179
|
+
Even if the user asks unrelated queries like "What are the vowels in English alphabet" or "How to cook", call this agent.
|
|
180
|
+
|
|
181
|
+
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.
|
|
182
|
+
_Example: "Create a chart"_
|
|
183
|
+
_Example: "Create a table"_`,Ps={id:"help",name:"Help Agent",description:$n,createGraph:kn,workspace:rt},Gs=g.Root({agentExecutionContext:g({reducer:B,default:()=>({userRequest:"",assignedTask:"",messages:[],priorSteps:[],sharedState:{}})}),outputMessage:g({reducer:Q,default:()=>""}),intent:g({reducer:(e,t)=>t})}),J={conversationId:""},_n=["linkChartView"],Cn=["knowledgeGraph"];function ae(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=_n.filter(a=>!(a in t));if(r.length)throw new Error(`Link Chart context missing: ${r.join(", ")}`);return t}function we(e){let t=e?.configurable?.context;if(!t||typeof t!="object")throw new Error("ArcgisKnowledgeAgent context missing");let r=Cn.filter(a=>!(a in t));if(r.length)throw new Error(`Knowledge Graph context missing: ${r.join(", ")}`);return t}var de=class{constructor(t){this.dataModel=t,this.kind="GraphQueryGenerationRequest",this.explainQuery=!0,this.schemaInformation=ue.fromDataModel(t)}},ue=class e{constructor(){this.schemaType="ArcgisGraphSchema",this.entityTypes=[],this.relationshipTypes=[],this.identifierInfo={mappingInfo:{identifierMapsTo:"UniformPropertyIdentifier",identifierPropertyName:"globalid"}}}static fromDataModel(t){let r=new e;for(let a of t.entityTypes)r.entityTypes.push(G.fromEntityType(a));for(let a of t.relationshipTypes)r.relationshipTypes.push(me.fromRelationshipType(a));return r.identifierInfo={mappingInfo:{identifierMapsTo:Nn(t.identifierInfo.identifierMappingInfo.identifierInfoType),identifierPropertyName:t.identifierInfo.identifierMappingInfo.uniformPropertyIdentifier.identifierPropertyName}},r.spatialReference=JSON.parse(JSON.stringify(t.spatialReference)),r}},G=class e{constructor(){this.name="",this.properties=[]}static fromEntityType(t){let r=new e;r.name=t.name,r.alias=t.alias?t.alias:void 0,r.role=Fn(t.role);for(let a of t.properties){let o={name:a.name,alias:a.alias?a.alias:void 0,fieldType:a.fieldType,role:Mn(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};r.properties.push(o)}return r}},me=class extends G{constructor(){super(...arguments),this.observedEndPoints=[]}static fromRelationshipType(t){let r=G.fromEntityType(t);r.observedEndPoints=[];for(let a of t.endPoints)r.observedEndPoints.push({originEntityType:a.originEntityType,destinationEntityType:a.destinationEntityType});return r}},Nn=e=>{switch(e){case"esriIdentifierInfoTypeUNSPECIFIED":return"UNSPECIFIED";case"esriIdentifierInfoTypeDatabaseNative":return"DatabaseNative";case"esriIdentifierInfoTypeUniformProperty":return"UniformPropertyIdentifier";default:return e}},Fn=e=>{switch(e){case"Regular":return"esriGraphNamedObjectRegular";case"Provenance":return"esriGraphNamedObjectProvenance";case"Document":return"esriGraphNamedObjectDocument";default:return e}};function Mn(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 An(e,t,r,a){let{graphQuery:o,explanation:n}=await be(e,t,r,a);return`Generated Graph Query:
|
|
184
|
+
${o}
|
|
185
|
+
|
|
186
|
+
Explanation: ${n}`}async function be(e,t,r,a){let o={message:e,context:new de(t)};J.conversationId&&(o.conversationId=J.conversationId),await h({text:"Attempting to generate a cypher query from your prompt..."},a);let n=await Ne(`${r}/chat`,{method:"post",body:JSON.stringify(o),headers:{"Content-Type":"application/json",token:Fe.findCredential(D.getDefault().url)?.token??""}});if(n.httpStatus!==200)throw new Error(`Graph query service returned an error: ${n.httpStatus}`,{cause:n.data});J.conversationId||(J.conversationId=n.data.conversationId);let s=!1,i=Date.now(),c=n.data.sequenceNumber,d="",u="",m=1;for(;!s;){await new Promise(b=>setTimeout(b,1e3)),await h({text:`Periodically requesting status of job from ArcGIS AI Services${"...".substring(0,m)}`},a),m=m%3+1;let p=await Ne(`${r}/chat`,{method:"post",body:JSON.stringify({conversationId:n.data.conversationId,inquiryId:n.data.inquiryId,ackSequenceNumber:c}),headers:{"Content-Type":"application/json",token:Fe.findCredential(D.getDefault().url)?.token??""}});if(p.httpStatus!==200)throw new Error(`Graph query service polling returned an error: ${p.httpStatus}`,{cause:p.data});if(p.data.context)d=p.data.context.graphQuery,u=p.data.message||"";else if(!p.data.hasMore)s=!0;else if(Date.now()-i>6e4)throw new Error("Graph query service polling timed out after 1 minute.");c=p.data.sequenceNumber}return{graphQuery:d,explanation:u}}function Y(e,t){if(!(!e||typeof e!="object")){if(Rn(e))for(let r of e.path)Y(r,t);else if(qn(e))t.set(`${e.typeName}__${e.id}`,{id:e.id,typeName:e.typeName});else if(Array.isArray(e))for(let r of e)Y(r,t);else if(Ln(e))for(let r of Object.values(e.properties??{}))Y(r,t)}}function qn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:"id"in e&&"typeName"in e}function Rn(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e&&"path"in e&&Array.isArray(e.path)}function Ln(e){return!e||typeof e!="object"||Array.isArray(e)||"id"in e?!1:"properties"in e&&typeof e.properties=="object"}function zn(e,t){let r=[];for(let a of[...t.dataModel.entityTypes,...t.dataModel.relationshipTypes]){let o=e.getMemberIdsByType(a.name);for(let n of o)r.push({id:n,typeName:a.name})}return r}var jn=async e=>{let t=new Map,r=e.resultRowsStream.getReader();for(;;){let{done:a,value:o}=await r.read();if(a)break;for(let n of o)for(let s of n)Y(s,t)}return Array.from(t.values())};async function Dn(e,t,r,a,o){let{graphQuery:n,explanation:s}=await be(e,t.dataModel,r,o);await h({text:`Attempting to execute query: ${n.substring(0,500)}${n.length>500?"...":""}`},o);let i=await Lt(t,new Ge({openCypherQuery:n}),{signal:o?.signal,timeout:o?.timeout}),c=await jn(i);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),a.goTo(a.map.diagramNodesExtent),`Link Chart updated successfully. Cypher Query used:
|
|
187
|
+
${n}
|
|
188
|
+
|
|
189
|
+
Explanation: ${s}`}async function On({prompt:e},t){let{knowledgeGraph:r}=we(t),{linkChartView:a}=ae(t),o=D.getDefault().helperServices,n=await R("arcgis_knowledge_current_lc_context"),s=zn(a.map,r),i=`${e}
|
|
190
|
+
|
|
191
|
+
${n}${JSON.stringify(s)}`;return await Dn(i,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Vn=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be run.")}),Bs=y(On,{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:Vn});async function Pn(e,t){return await t.map.applyLayout(e),`Successfully applied layout: ${e}.`}async function Gn({layout:e},t){let{linkChartView:r}=ae(t);return await Pn(e,r)}var Bn=l.object({layout:l.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")}),Qs=y(Gn,{name:"applyLayout",description:"Apply a diagram layout to the link chart",schema:Bn});function Qn(e,t){return t.map.changeNonspatialDataDisplay(e),`Successfully applied nonspatial visibility setting: ${e}.`}function Un({setting:e},t){let{linkChartView:r}=ae(t);return Qn(e,r)}var Wn=l.object({setting:l.enum(["hidden","visible"]).describe("The setting of nonspatial visibility")}),Us=y(Un,{name:"changeNonspatialVisibility",description:"Change whether or not nonspatial data is visible in the link chart. The value must be either 'hidden' or 'visible'.",schema:Wn});async function Kn(e,t,r,a,o){let{graphQuery:n,explanation:s}=await be(e,t.dataModel,r,o);await h({text:`Attempting to create link chart from derived query: ${n}`},o);let i=await zt.fromCypherQuery(t,new Ge({openCypherQuery:n}));return await h({text:"Link chart created successfully, loading..."},o),a.map=i,await i.load(),await a.when(),`Link chart created successfully. Cypher Query used to create the link chart:
|
|
192
|
+
${n}
|
|
193
|
+
|
|
194
|
+
Explanation: ${s}`}async function Hn({prompt:e},t){let{knowledgeGraph:r}=we(t),{linkChartView:a}=ae(t),o=D.getDefault().helperServices;return await Kn(e,r,`${o.aiAssistantServices.url}${o.aiAssistantServices.graphQueryAssistant}`,a,t)}var Zn=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be transformed into a link chart visualization.")}),Ws=y(Hn,{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:Zn});async function Jn({prompt:e},t){let{knowledgeGraph:r}=we(t),a=D.getDefault().helperServices;return await An(e,r.dataModel,`${a.aiAssistantServices.url}${a.aiAssistantServices.graphQueryAssistant}`,t)}var Yn=l.object({prompt:l.string().describe("The user's inquiry into the knowledge graph that needs to be translated into a cypher query.")}),Ks=y(Jn,{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:Yn});var Hs=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).
|
|
195
|
+
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.
|
|
196
|
+
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,
|
|
197
|
+
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
|
|
198
|
+
that exist out from specified entities and adding those to the link chart, changing whether or not nonspatial data is visible, or changing the layout of the link chart.
|
|
199
|
+
This agent is designed to handle requests that manipulate the specific link chart.
|
|
200
|
+
For knowledge graph data more generally, the agent can generate Open Cypher queries based on user prompts that represent inquiries into the data of the knowledge service and its graph database,
|
|
201
|
+
and can alternatively use those queries to create a new link chart visualization from the results if requested.
|
|
202
|
+
|
|
203
|
+
Supported actions:
|
|
204
|
+
- **Change or Apply Layout**: Changes the current layout visualization strategy of the link chart (e.g., "Change the layout to basic-grid", "Apply hierarchical layout"). Valid layout types include organic-standard, organic-community, basic-grid, hierarchical-bottom-to-top, radial-root-centric, tree-left-to-right, geographic-organic-standard, chronological-mono-timeline. A best effort should be made to transform the user's request into one of these layout types.
|
|
205
|
+
- **Change Nonspatial Data Visibility**: Changes whether or not nonspatial data is visible on the link chart (e.g., "Show nonspatial data", "Hide nonspatial data"). Valid settings are "hidden" and "visible". A best effort should be made to transform the user's request into one of these settings.
|
|
206
|
+
- **Generate a cypher query**: 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. The user should explicitly request that a cypher query be returned - if they do not, the purpose of the query is for one of the other tools or skills.
|
|
207
|
+
- **Create a New Link Chart from a user prompt**: Identifies that the users prompt is an inquiry into the data of the knowledge service and its graph database and creates a new link chart from the results. The user should have requested that a link chart be created or made(or similar term) from their prompt
|
|
208
|
+
- **Add Records (entities or relationships)**: Identifies that the users prompt is an inquiry into the data of the knowledge graph service and its graph database, and that the user wants to take the result of the inquiry and add those entities and/or relationships to the link chart. The generated query should be syntactically correct and optimized for performance.
|
|
209
|
+
|
|
210
|
+
_example: "Change the layout to hierarchical-bottom-to-top"_
|
|
211
|
+
_example: "Apply radial-root-centric layout"_
|
|
212
|
+
_example: "Show nonspatial data"_
|
|
213
|
+
_example: "Hide nonspatial data"_
|
|
214
|
+
_example: "Turn off nonspatial visibility"_
|
|
215
|
+
_example: "Generate a cypher query to find all entities connected to 'Entity A' via 'Relationship X' that were created after 2020"_
|
|
216
|
+
_example: "Generate a query to find all employees of Company Esri who joined after 2015 and are located in California"_
|
|
217
|
+
_example: "Tell me how to find all products supplied by Supplier Y that have a price greater than $1000"_
|
|
218
|
+
_example: "Create a new link chart showing all entities related to 'Entity B' through 'Relationship Y'"_
|
|
219
|
+
_example: "Find all people who work for Microsoft and put them on a new link chart"_
|
|
220
|
+
_example: "Add all entities connected to 'Entity C' via 'Relationship Z' to the current link chart"_
|
|
221
|
+
_example: "Add all the people who work for Esri to the current link chart, and all the cars that they drive"_
|
|
222
|
+
_example: "Find all the products supplied by Supplier X and add them to my visualization"_
|
|
223
|
+
_example: "Expand the link chart from 'Entity D' to show its direct connections"_
|
|
224
|
+
_example: "Find all the cars and then add everything up to two hops away from them on the link chart"_
|
|
225
|
+
_example: "Connect Emma and Rob on the link chart if there is a relationship between them"
|
|
226
|
+
_example: "Discover and add all the relationships originating at 'Entity E' to the link chart"_`;return{a:Os,b:Vs,c:ze,d:Ps}},"Graphic","geometry/Point","geometry/Extent","symbols/PictureMarkerSymbol","rest/locator","portal/Portal","config","layers/support/FeatureEffect","layers/support/FeatureFilter","geometry/operators/unionOperator","intl","smartMapping/statistics/summaryStatistics","smartMapping/statistics/uniqueValues","rest/support/TopFeaturesQuery","rest/support/TopFilter","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","rest/knowledgeGraphService","WebLinkChart",a)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import{a as i,b as l}from"./EUNEQNYC.js";import{a as f}from"./B3E2XBTX.js";import"./YGW7TUNX.js";import{g as m,h as a,v as g,w as o,y as b}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";var p=m`:host{display:block;container-type:inline-size}.container{display:flex;flex-direction:column;align-items:flex-start;gap:var(--calcite-spacing-sm);width:100%;text-align:left}.icon{padding:var(--calcite-spacing-sm);border-radius:var(--calcite-spacing-xl);background:var(--calcite-color-brand);color:var(--calcite-color-foreground-1)}.content-container{display:flex;flex:1;flex-direction:column;width:100%;gap:var(--calcite-spacing-md)}.content,.blocks{display:flex;flex-direction:column;gap:var(--calcite-spacing-sm)}@container (min-width: 480px){.container{max-width:80%}}`;function h({message:s}){let e=new Map;if(!s)return e;let t=i(s.id);return e.set(t,{data:{message:s},name:"message",slotName:t}),s.blocks?.forEach((r,n)=>{let d=l(s.id,n);e.set(d,{data:{block:r,index:n,message:s},name:"block",slotName:d})}),e}var c=class extends g{constructor(){super(...arguments),this.arcgisSlottableRequest=f(this,["message"],h),this.feedbackEnabled=!1,this.logEnabled=!1,this.copyEnabled=!1,this.readAloudEnabled=!1,this.footerDisabled=!1}static{this.properties={feedbackEnabled:5,logEnabled:5,copyEnabled:5,readAloudEnabled:5,footerDisabled:5,message:0}}static{this.styles=p}_renderContent(){let e=this.message,t=e?.id;if(t)return a`<div class="content"><slot name=${i(t)??o}></slot>${e.blocks?.length?a`<div class="blocks">${e.blocks.map((r,n)=>a`<slot name=${l(t,n)??o}></slot>`)}</div>`:null}</div>`}_renderFooter(){return a`<arcgis-assistant-message-footer .message=${this.message} .feedbackEnabled=${this.feedbackEnabled} .logEnabled=${this.logEnabled} .copyEnabled=${this.copyEnabled} .readAloudEnabled=${this.readAloudEnabled}></arcgis-assistant-message-footer>`}render(){return a`<div class="container"><slot name=icon><calcite-icon icon=effects class="icon" scale=s></calcite-icon></slot><div class="content-container"><slot name=content>${this._renderContent()}</slot>${this.footerDisabled?null:a`<slot name=footer>${this._renderFooter()}</slot>`}</div></div>`}};b("arcgis-assistant-message",c);export{c as ArcgisAssistantMessage};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import c from"./
|
|
2
|
+
import c from"./SOJ4DKGV.js";import b from"./KHCTRS6Z.js";import"./PLPJJRCP.js";import{a as r,c as a}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as s,y as e}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{d:i}])=>{var t=class extends s{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-help-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-help-agent"),a(this)}};e("arcgis-assistant-help-agent",t);return t},b,c)
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
-
import c from"./
|
|
2
|
+
import c from"./SOJ4DKGV.js";import b from"./KHCTRS6Z.js";import"./PLPJJRCP.js";import{a as r,c as e}from"./B4DEC7PH.js";import"./KVH3PDVW.js";import"./YGW7TUNX.js";import{v as a,y as s}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([,{b:i}])=>{var t=class extends a{constructor(){super(...arguments),this.agent=i}static{this.properties={referenceElement:1}}#t;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=r(this,"arcgis-assistant-data-exploration-agent"),e(this)}};s("arcgis-assistant-data-exploration-agent",t);return t},b,c)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import{a as f}from"./YUZDB6IX.js";import"./B3E2XBTX.js";import"./YGW7TUNX.js";import{g as d,h as r,n,t as o,u as l,v as g,y as m}from"./AKEZZ3RP.js";import"./CFDTXKJ6.js";export default $arcgis.t(([v])=>{var y=d`.input-container{display:flex;flex-direction:column}.footer-start{display:flex;gap:var(--calcite-spacing-md);flex-wrap:wrap;align-items:center}.footer-end{display:flex;gap:var(--calcite-spacing-md);align-items:center}.status-indicator{width:9px;height:9px;border-radius:100%;background-color:var(--calcite-color-status-success)}.status-indicator[data-status=working]{background-color:var(--calcite-color-status-warning)}.status-indicator[data-status=error]{background-color:var(--calcite-color-status-danger)}.status-text{text-transform:capitalize}`,c=class extends g{constructor(){super(...arguments),this.#s=o(),this.#a=o(),this.#t=-1,this.#e="",this.#i=t=>{t.stopPropagation();let s=t.detail;this._setDraftValue(s.value),s.focusInput&&this.#s.value&&this.#s.value.setFocus()},this.#r=t=>{let s=t.target.value??"";this.inputValue=s,this.#e=s},this._messages=f({blocking:!0}),this.keyboardShortcutsDisabled=!1,this.awaitingResponse=!1,this.inputValue="",this.voiceInputEnabled=!1,this.messages=new v([]),this.arcgisCancel=n(),this.arcgisSubmit=n()}static{this.properties={_userMessages:16,keyboardShortcutsDisabled:5,entryPlaceholder:1,awaitingResponse:5,inputValue:1,status:1,voiceInputEnabled:5,messages:0}}static{this.styles=y}#s;#a;#t;#e;#i;#r;get _userMessages(){return this.messages.toArray().filter(t=>t.role==="user").map(({content:t})=>t)}async submitMessage(){if(this.awaitingResponse){this.arcgisCancel.emit();return}let t=this.inputValue.trim();t&&(this.arcgisSubmit.emit(t),this.inputValue="",this.#t=-1,this.#e="",this.#a.value?.clearDraftSession(),this.#s.value&&await this.#s.value.setFocus())}loaded(){this.manager.onLifecycle(()=>(this.el.addEventListener("arcgisVoiceInputDraftChange",this.#i),{remove:()=>{this.el.removeEventListener("arcgisVoiceInputDraftChange",this.#i)}}))}async _navigateHistory(t,s){let i=this.#s.value;if(!i)return;let e=this._userMessages;if(e.length===0)return;let u=i.value??"",h=i.shadowRoot?.querySelector("textarea"),a=h?.selectionStart,p=h?.selectionEnd;if(!(a==null||p==null)&&!(a!==p||t==="up"&&a!==0||t==="down"&&a!==u.length)){if(t==="up"){this.#t===-1?(this.#e=u,this.#t=e.length-1):this.#t=Math.max(0,this.#t-1),this.inputValue=e[this.#t]??"",s.preventDefault();return}this.#t!==-1&&(this.#t<e.length-1?(this.#t+=1,this.inputValue=e[this.#t]??""):(this.#t=-1,this.inputValue=this.#e),s.preventDefault())}}_setDraftValue(t){this.inputValue=t,this.#t=-1,this.#e=t}render(){return r`<div class="input-container"><calcite-text-area .value=${this.inputValue} .placeholder=${this.entryPlaceholder??this._messages.entryPlaceholder} resize=vertical @calciteTextAreaInput=${this.#r} @keydown=${async t=>{t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||this.keyboardShortcutsDisabled||(t.key==="Enter"?(t.preventDefault(),await this.submitMessage()):t.key==="ArrowUp"?await this._navigateHistory("up",t):t.key==="ArrowDown"&&await this._navigateHistory("down",t))}} ${l(this.#s)}><div slot=footer-start class="footer-start"><slot name=entry-actions-start></slot></div><div slot=footer-end class="footer-end">${this.voiceInputEnabled?r`<arcgis-assistant-speech-input .awaitingResponse=${this.awaitingResponse} .inputValue=${this.inputValue} ${l(this.#a)}></arcgis-assistant-speech-input>`:null}<slot name=entry-actions-end></slot></div></calcite-text-area></div>`}};m("arcgis-assistant-chat-entry",c);return c},"core/Collection")
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
|
|
2
|
+
import"./CFDTXKJ6.js";var e=`## GIS Agent Orchestrator
|
|
3
|
+
|
|
4
|
+
You are an orchestrator for an ArcGIS Maps SDK for JavaScript system.
|
|
5
|
+
|
|
6
|
+
Your job is to decide the single best next agent to execute for the current step.
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Inputs
|
|
11
|
+
|
|
12
|
+
You are given:
|
|
13
|
+
|
|
14
|
+
- the latest user request
|
|
15
|
+
- relevant chat history
|
|
16
|
+
- the list of registered agents
|
|
17
|
+
- optional prior steps from earlier agent executions
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Output
|
|
22
|
+
|
|
23
|
+
Return either:
|
|
24
|
+
|
|
25
|
+
- one decision with:
|
|
26
|
+
1. \`agentId\` \u2014 the next agent to execute
|
|
27
|
+
2. \`assignedTask\` \u2014 a clear, actionable task for that agent
|
|
28
|
+
3. \`requiresFollowUp\` \u2014 whether another orchestration step will likely be needed after this agent succeeds
|
|
29
|
+
|
|
30
|
+
- or \`null\` if no registered agent applies
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Important
|
|
35
|
+
|
|
36
|
+
- Return \`null\` only when the request is clearly outside the scope of all registered agents.
|
|
37
|
+
- If any agent can take the next useful step, select the best one instead of returning \`null\`.
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Context
|
|
42
|
+
|
|
43
|
+
### Latest user request
|
|
44
|
+
|
|
45
|
+
{userRequest}
|
|
46
|
+
|
|
47
|
+
### Registered agents
|
|
48
|
+
|
|
49
|
+
Format:
|
|
50
|
+
{{id: string, name: string, description: string}}[]
|
|
51
|
+
|
|
52
|
+
{registeredAgents}
|
|
53
|
+
|
|
54
|
+
### Prior steps
|
|
55
|
+
|
|
56
|
+
Each step has:
|
|
57
|
+
|
|
58
|
+
- \`agentId: string\`
|
|
59
|
+
- \`assignedTask: string\`
|
|
60
|
+
- \`summary: string\`
|
|
61
|
+
- \`status: "success" | "failed" | "unknown"\`
|
|
62
|
+
|
|
63
|
+
Use prior steps to:
|
|
64
|
+
|
|
65
|
+
- Avoid repeating work that has already succeeded
|
|
66
|
+
- Retry or adjust steps that failed when appropriate
|
|
67
|
+
|
|
68
|
+
{priorSteps}
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Rules
|
|
73
|
+
|
|
74
|
+
- Focus primarily on the latest user request.
|
|
75
|
+
- Use relevant chat history only when the latest request clearly depends on earlier context; otherwise ignore it.
|
|
76
|
+
- Use prior steps to determine what has already been attempted or completed.
|
|
77
|
+
- Do not plan the full workflow up front. Only decide the next best step.
|
|
78
|
+
- Prefer an agent that can directly complete the user\u2019s request.
|
|
79
|
+
- Only break the request into multiple steps when necessary.
|
|
80
|
+
- When multiple agents could help, choose the best fit instead of returning \`null\`.
|
|
81
|
+
- Base the choice on the registered agent descriptions, not on whether the user used exact matching keywords.
|
|
82
|
+
- If no agent can fully complete the request, but one agent can take the next useful step, choose that agent and set \`requiresFollowUp\` to \`true\`.
|
|
83
|
+
- Do NOT reuse constraints from prior steps unless the current user request explicitly requires them.
|
|
84
|
+
- Each step must reflect the current user request exactly.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## Constraint Interpretation
|
|
89
|
+
|
|
90
|
+
Interpret the user\u2019s wording precisely:
|
|
91
|
+
|
|
92
|
+
- Do not substitute one type of constraint for another (e.g., distance vs containment, range vs exact match, etc.)
|
|
93
|
+
- If the user specifies a constraint, use it exactly
|
|
94
|
+
- If the user does not specify a constraint, do not assume or infer one
|
|
95
|
+
|
|
96
|
+
Do not reinterpret the request into a different form.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Assigned Task Guidelines (IMPORTANT)
|
|
101
|
+
|
|
102
|
+
- The \`assignedTask\` must match the user\u2019s request exactly in meaning
|
|
103
|
+
- Do not add, remove, or transform constraints
|
|
104
|
+
- Do not substitute one type of constraint for another
|
|
105
|
+
- If a constraint is not explicitly stated, do not assume one
|
|
106
|
+
|
|
107
|
+
- Keep the task short, specific, and directly executable
|
|
108
|
+
- Keep wording close to the user\u2019s request with minimal transformation
|
|
109
|
+
- Use only information explicitly present in the user request or provided context
|
|
110
|
+
|
|
111
|
+
- The \`assignedTask\` may represent only part of the user\u2019s request when multiple steps are necessary
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## requiresFollowUp Guidelines
|
|
116
|
+
|
|
117
|
+
- \`requiresFollowUp\` should indicate a likely next agent step, not uncertainty about the current request
|
|
118
|
+
- Set \`requiresFollowUp\` to \`true\` only when another orchestration step will likely be needed after this agent succeeds
|
|
119
|
+
- Set \`requiresFollowUp\` to \`false\` when a successful result from this agent would likely complete the user-visible task
|
|
120
|
+
`;export{e as default};
|