@arcgis/ai-components 5.2.0-next.3 → 5.2.0-next.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-utils/FunctionAgent.d.ts +2 -2
- package/dist/agent-utils/LLMAgent.d.ts +2 -2
- package/dist/agent-utils/LLMAgent.js +23 -22
- package/dist/agent-utils/WorkflowAgent.d.ts +2 -2
- package/dist/agent-utils/index.d.ts +177 -0
- package/dist/agent-utils/index.js +167 -0
- package/dist/agent-utils/middlewares/trace.d.ts +2 -0
- package/dist/agent-utils/middlewares/trace.js +25 -33
- package/dist/agent-utils/tools/FunctionTool.d.ts +2 -2
- package/dist/agent-utils/types.d.ts +36 -7
- package/dist/agent-utils/workflows/ConditionalWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/LoopWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/ParallelWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/RouterWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/SequentialWorkflow.d.ts +2 -2
- package/dist/agent-utils/workflows/SwitchWorkflow.d.ts +2 -2
- package/dist/cdn/27NEUQN3.js +2 -0
- package/dist/cdn/2NMR43NW.js +2 -0
- package/dist/cdn/3AXQTBIA.js +134 -0
- package/dist/cdn/434TAA3J.js +2 -0
- package/dist/cdn/4I4MCV7V.js +71 -0
- package/dist/cdn/4RZPOYZ7.js +9 -0
- package/dist/cdn/5SBLS4NW.js +2 -0
- package/dist/cdn/{AMP6IALT.js → 5W7S2RS4.js} +1 -1
- package/dist/cdn/6LZ6GOHF.js +56 -0
- package/dist/cdn/7IFCBXV7.js +2 -0
- package/dist/cdn/ADYIXCSG.js +2 -0
- package/dist/cdn/AFLQZIKS.js +180 -0
- package/dist/cdn/AMVOJNWN.js +2 -0
- package/dist/cdn/C7E7MJSR.js +2 -0
- package/dist/cdn/CAECQD75.js +2 -0
- package/dist/cdn/CIW3QMKV.js +2 -0
- package/dist/cdn/CJIV4KJZ.js +179 -0
- package/dist/cdn/CVHJMR5X.js +2 -0
- package/dist/cdn/DEAYZ3MK.js +2 -0
- package/dist/cdn/{H7422XUG.js → E2HENO3T.js} +1 -1
- package/dist/cdn/E7TMP4YV.js +3 -0
- package/dist/cdn/EBRNMPPO.js +48 -0
- package/dist/cdn/FWU6DFIB.js +2 -0
- package/dist/cdn/HBYZSLEZ.js +22 -0
- package/dist/cdn/HOCTVCHH.js +2 -0
- package/dist/cdn/{4HU7735A.js → HXOSLGWU.js} +6 -4
- package/dist/cdn/I64KIZG3.js +2 -0
- package/dist/cdn/IB4WTK74.js +2 -0
- package/dist/cdn/IC5P5NYY.js +2 -0
- package/dist/cdn/IGZWQJW7.js +3 -0
- package/dist/cdn/IKEF7ZHH.js +181 -0
- package/dist/cdn/IXAKT6L3.js +2 -0
- package/dist/cdn/JEIMRNYM.js +2 -0
- package/dist/cdn/JN744CAW.js +2 -0
- package/dist/cdn/KRE4U7V7.js +2 -0
- package/dist/cdn/{NE7E52YR.js → KTK4HNL2.js} +8 -2
- package/dist/cdn/L77BTGXY.js +2 -0
- package/dist/cdn/LEPJUN3X.js +22 -0
- package/dist/cdn/LODKJRS4.js +2 -0
- package/dist/cdn/M3SWPT3M.js +2 -0
- package/dist/cdn/MAV3DW27.js +4 -0
- package/dist/cdn/NOJYPREL.js +3 -0
- package/dist/cdn/NXKKG5TK.js +2 -0
- package/dist/cdn/O3F47IO5.js +2 -0
- package/dist/cdn/O7TGCM5P.js +6 -0
- package/dist/cdn/PBTINZTK.js +65 -0
- package/dist/cdn/PKHQW7QU.js +18 -0
- package/dist/cdn/PSWI3MFB.js +2 -0
- package/dist/cdn/Q73PK7Q7.js +2 -0
- package/dist/cdn/Q7TL5Q5N.js +2 -0
- package/dist/cdn/QSA4T3BU.js +2 -0
- package/dist/cdn/RMLXVQZ5.js +2 -0
- package/dist/cdn/RX45PCYB.js +9 -0
- package/dist/cdn/S27EJSLC.js +14 -0
- package/dist/cdn/SMADRJ67.js +2 -0
- package/dist/cdn/{ZLXN7NMF.js → T537PKP4.js} +9 -7
- package/dist/cdn/{X2ZDYHCG.js → TNMXWUXU.js} +9 -4
- package/dist/cdn/TSEQVE2H.js +36 -0
- package/dist/cdn/VKU4WAQV.js +2 -0
- package/dist/cdn/W2IHPJ54.js +34 -0
- package/dist/cdn/W2JAKE2M.js +2 -0
- package/dist/cdn/WAVKMZA6.js +2 -0
- package/dist/cdn/WDE3HN7K.js +2 -0
- package/dist/cdn/WH6QQK6N.js +2 -0
- package/dist/cdn/WNS5ZUF5.js +2 -0
- package/dist/cdn/{FL4W4VYN.js → X7GE26KU.js} +16 -0
- package/dist/cdn/XVQJBUMY.js +2 -0
- package/dist/cdn/YJ3QQXF6.js +2 -0
- package/dist/cdn/YRBANNQ5.js +2 -0
- package/dist/cdn/YYY7HKYX.js +2 -0
- package/dist/cdn/ZEYIBYSF.js +66 -0
- package/dist/cdn/ZMSJQB65.js +99 -0
- package/dist/cdn/ZOSUDIJH.js +2 -0
- package/dist/cdn/ZPLFFLPF.js +2 -0
- package/dist/cdn/agent-utils/index.js +2 -0
- package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +3 -0
- package/dist/cdn/agent-utils/middlewares/middleware.js +2 -0
- package/dist/cdn/agent-utils/middlewares/trace.js +2 -0
- package/dist/cdn/index.js +1 -1
- package/dist/cdn/main.css +1 -1
- package/dist/chunks/adapter.js +1794 -1597
- package/dist/chunks/arcgisKnowledgeGraph.js +126 -71
- package/dist/chunks/arcgis_knowledge_current_lc_context.js +19 -2
- package/dist/chunks/arcgis_knowledge_current_map_context.js +31 -2
- package/dist/chunks/arcgis_knowledge_cypher_query_prompt.js +102 -0
- package/dist/chunks/arcgis_knowledge_summarize_result_prompt.js +116 -27
- package/dist/chunks/converterUtils.js +39 -32
- package/dist/chunks/dataExplorationGraph.js +139 -113
- package/dist/chunks/data_explore_query_prompt.js +9 -4
- package/dist/chunks/generateLayerDescriptions.js +231 -191
- package/dist/chunks/helpGraph.js +17 -13
- package/dist/chunks/help_prompt.js +34 -17
- package/dist/chunks/index.js +11 -0
- package/dist/chunks/intent_prompt.js +16 -0
- package/dist/chunks/layerStylingGraph.js +24 -20
- package/dist/chunks/navigationGraph.js +33 -28
- package/dist/chunks/navigation_intent_prompt.js +8 -2
- package/dist/chunks/orchestrator.js +267 -226
- package/dist/chunks/slottableRequestUtils.js +3 -7
- package/dist/chunks/state.js +1 -1
- package/dist/chunks/summarize_query_response_prompt.js +9 -7
- package/dist/chunks/toolCallResponse.js +12 -9
- package/dist/chunks/utils2.js +8 -8
- package/dist/components/arcgis-assistant/customElement.d.ts +27 -0
- package/dist/components/arcgis-assistant/customElement.js +385 -152
- package/dist/components/arcgis-assistant/index.js +2 -3
- package/dist/components/arcgis-assistant/types.d.ts +14 -1
- package/dist/components/arcgis-assistant-agent/customElement.js +5 -1
- package/dist/components/arcgis-assistant-chat/customElement.d.ts +8 -2
- package/dist/components/arcgis-assistant-chat/customElement.js +23 -18
- package/dist/components/arcgis-assistant-chat-entry/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-chat-entry/customElement.js +25 -18
- package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +11 -5
- package/dist/components/arcgis-assistant-help-agent/customElement.js +8 -2
- package/dist/components/arcgis-assistant-interrupt/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-interrupt/customElement.js +12 -8
- package/dist/components/arcgis-assistant-interrupt-preview/customElement.js +20 -0
- package/dist/components/arcgis-assistant-interrupt-preview/index.js +2 -0
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.d.ts +7 -7
- package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +17 -11
- package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +10 -4
- package/dist/components/arcgis-assistant-message/customElement.d.ts +23 -0
- package/dist/components/arcgis-assistant-message/customElement.js +28 -26
- package/dist/components/arcgis-assistant-message/index.d.ts +1 -0
- package/dist/components/arcgis-assistant-message/index.js +2 -0
- package/dist/components/arcgis-assistant-message-block/customElement.d.ts +1 -1
- package/dist/components/arcgis-assistant-message-block/customElement.js +18 -11
- package/dist/components/arcgis-assistant-message-block/index.js +1 -0
- package/dist/components/arcgis-assistant-message-feedback/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-footer/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-loading/customElement.d.ts +8 -1
- package/dist/components/arcgis-assistant-message-loading/customElement.js +8 -8
- package/dist/components/arcgis-assistant-message-loading/index.js +1 -0
- package/dist/components/arcgis-assistant-message-log/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-read-aloud/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-message-text/customElement.d.ts +5 -1
- package/dist/components/arcgis-assistant-message-text/customElement.js +12 -12
- package/dist/components/arcgis-assistant-navigation-agent/customElement.js +11 -5
- package/dist/components/arcgis-assistant-speech-input/customElement.d.ts +6 -1
- package/dist/components/arcgis-assistant-suggested-prompts/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-suggested-prompts/customElement.js +8 -8
- package/dist/components/arcgis-assistant-user-message/customElement.d.ts +4 -1
- package/dist/components/arcgis-assistant-user-message/customElement.js +10 -8
- 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 +4 -0
- package/dist/loader.js +7 -6
- package/dist/types/lumina.d.ts +11 -5
- package/dist/types/preact.d.ts +12 -5
- package/dist/types/react.d.ts +13 -5
- package/dist/types/stencil.d.ts +11 -5
- package/dist/utils/index.d.ts +85 -42
- package/dist/utils/index.js +54 -49
- package/package.json +8 -7
- package/dist/cdn/2AXF774U.js +0 -2
- package/dist/cdn/3PKJWIC3.js +0 -2
- package/dist/cdn/462JBSEV.js +0 -422
- package/dist/cdn/5QAHYX7Y.js +0 -5
- package/dist/cdn/7BCR6TUO.js +0 -2
- package/dist/cdn/7GH7VSB2.js +0 -2
- package/dist/cdn/7PLV4QH6.js +0 -2
- package/dist/cdn/AO7BQHKC.js +0 -2
- package/dist/cdn/AXDZBBNL.js +0 -45
- package/dist/cdn/DDLZOMUY.js +0 -2
- package/dist/cdn/DHOVCT6R.js +0 -2
- package/dist/cdn/F2AHA4GB.js +0 -54
- package/dist/cdn/FHVXO2WG.js +0 -166
- package/dist/cdn/FX5JFRDL.js +0 -2
- package/dist/cdn/GSEPHN3A.js +0 -106
- package/dist/cdn/HB5A5R2E.js +0 -2
- package/dist/cdn/JY6LLOUJ.js +0 -22
- package/dist/cdn/KMQ3SP4I.js +0 -5
- package/dist/cdn/MDVYQQUG.js +0 -14
- package/dist/cdn/MH5RPXHM.js +0 -2
- package/dist/cdn/NAUXSHIE.js +0 -72
- package/dist/cdn/NVI3I46B.js +0 -2
- package/dist/cdn/OAVEHGB6.js +0 -2
- package/dist/cdn/OH64RMOR.js +0 -4
- package/dist/cdn/ON2V5XI2.js +0 -3
- package/dist/cdn/P6OPJQMC.js +0 -3
- package/dist/cdn/QR54T33D.js +0 -2
- package/dist/cdn/RVOAPUBN.js +0 -2
- package/dist/cdn/S6W6HV4T.js +0 -36
- package/dist/cdn/SXDLXCIM.js +0 -2
- package/dist/cdn/USMDJUFS.js +0 -2
- package/dist/cdn/V2P4AIGG.js +0 -2
- package/dist/cdn/V5YEZSRY.js +0 -16
- package/dist/cdn/Y333DGV6.js +0 -2
- package/dist/cdn/YY2SBO3V.js +0 -2
|
@@ -3,13 +3,43 @@ import type { BaseChannel, BinaryOperatorAggregate } from "@langchain/langgraph/
|
|
|
3
3
|
import type { AnnotationRoot, StateDefinitionInit, StateGraph } from "@langchain/langgraph/web";
|
|
4
4
|
import type { AgentExecutionContext, AgentRegistration, AgentStatus } from "../utils/index.js";
|
|
5
5
|
|
|
6
|
-
/** @internal */
|
|
7
6
|
export type AgentData = Record<string, unknown>;
|
|
8
7
|
|
|
9
|
-
/** @internal */
|
|
10
8
|
export type EmptyAgentData = Record<never, never>;
|
|
11
9
|
|
|
12
|
-
/** @
|
|
10
|
+
/** @internal */
|
|
11
|
+
export type ZodModule = {
|
|
12
|
+
z: typeof z;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export type SchemaPrimitiveFieldType = "boolean" | "number" | "string";
|
|
16
|
+
|
|
17
|
+
export type SchemaArrayItemDefinition = SchemaFieldDefinition | SchemaPrimitiveFieldType;
|
|
18
|
+
|
|
19
|
+
export type SchemaFieldDefinition = ({
|
|
20
|
+
type: "array";
|
|
21
|
+
itemType: SchemaArrayItemDefinition;
|
|
22
|
+
} | { type: "boolean" | "number"; } | {
|
|
23
|
+
type: "object";
|
|
24
|
+
fields: SchemaDefinition;
|
|
25
|
+
} | {
|
|
26
|
+
type: "string";
|
|
27
|
+
enum?: readonly string[];
|
|
28
|
+
}) & {
|
|
29
|
+
description?: string;
|
|
30
|
+
required?: boolean;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type SchemaDefinition = Record<string, SchemaFieldDefinition>;
|
|
34
|
+
|
|
35
|
+
export type SchemaDefinitionData<TDefinition extends SchemaDefinition> = {
|
|
36
|
+
[K in keyof TDefinition as TDefinition[K] extends { required: true; } ? K : never]: SchemaFieldData<TDefinition[K]>;
|
|
37
|
+
} &
|
|
38
|
+
{
|
|
39
|
+
[K in keyof TDefinition as TDefinition[K] extends { required: true; } ? never : K]?: SchemaFieldData<TDefinition[K]>;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** @privateRemark All agents are orchestrator-driven, so these channels exist for every agent graph. */
|
|
13
43
|
export type AgentRuntimeState = {
|
|
14
44
|
agentExecutionContext: AgentExecutionContext;
|
|
15
45
|
/** The outputMessage is a string representing the output of an agent execution. */
|
|
@@ -101,7 +131,6 @@ export type AgentNodeUpdate<TInput extends AgentData, TOutput extends AgentData>
|
|
|
101
131
|
* AgentStateAnnotation defines the shape of the agent state used in LangGraph nodes, including both the built-in runtime channels
|
|
102
132
|
* and any custom fields defined by the agent.
|
|
103
133
|
*
|
|
104
|
-
* @internal
|
|
105
134
|
* @since 5.1
|
|
106
135
|
*/
|
|
107
136
|
export type AgentStateAnnotation<TState extends AgentData> = AnnotationRoot<{
|
|
@@ -123,7 +152,6 @@ export type RunnableUpdate<TState extends AgentData> = Partial<TState> extends o
|
|
|
123
152
|
/**
|
|
124
153
|
* Internal type representing the compiled graph used for agent execution.
|
|
125
154
|
*
|
|
126
|
-
* @internal
|
|
127
155
|
* @since 5.1
|
|
128
156
|
*/
|
|
129
157
|
export type TypedStateGraph<TState extends AgentData> = StateGraph<StateDefinitionInit, AgentGraphState<TState>, RunnableUpdate<AgentGraphState<TState>>, string>;
|
|
@@ -132,7 +160,6 @@ export type TypedStateGraph<TState extends AgentData> = StateGraph<StateDefiniti
|
|
|
132
160
|
* The shape of the `createGraph` function used by agents to generate their internal graph representation.
|
|
133
161
|
* This function is responsible for defining the nodes and edges of the graph, as well as any associated state and middleware.
|
|
134
162
|
*
|
|
135
|
-
* @internal
|
|
136
163
|
* @since 5.1
|
|
137
164
|
*/
|
|
138
165
|
export type AgentCreateGraph<TState extends AgentData> = () => TypedStateGraph<TState>;
|
|
@@ -149,4 +176,6 @@ export type GraphEdge<S extends AgentData> = {
|
|
|
149
176
|
} | {
|
|
150
177
|
from: string;
|
|
151
178
|
to: string;
|
|
152
|
-
};
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export type SchemaFieldData<TField extends SchemaFieldDefinition> = TField extends { type: "string"; } ? TField["enum"] extends readonly (infer TValue extends string)[] ? TValue : string : TField extends { type: "array"; } ? (TField["itemType"] extends "string" ? string : TField["itemType"] extends "number" ? number : TField["itemType"] extends "boolean" ? boolean : TField["itemType"] extends SchemaFieldDefinition ? SchemaFieldData<TField["itemType"]> : never)[] : TField extends { type: "object"; } ? SchemaDefinitionData<TField["fields"]> : TField extends { type: "number"; } ? number : boolean;
|
|
@@ -26,7 +26,7 @@ export type ConditionDecider<TState extends AgentData = AgentData> = (state: Age
|
|
|
26
26
|
* @since 5.1
|
|
27
27
|
*/
|
|
28
28
|
export class ConditionalWorkflow<TState extends AgentData = AgentData> extends BaseWorkflow<TState> {
|
|
29
|
-
constructor(properties:
|
|
29
|
+
constructor(properties: ConditionalWorkflowConstructProperties<TState>);
|
|
30
30
|
/**
|
|
31
31
|
* Must contain exactly two agents: `[trueAgent, falseAgent]`. The first agent is executed when
|
|
32
32
|
* the condition is true, the second when the condition is false.
|
|
@@ -69,4 +69,4 @@ export class ConditionalWorkflow<TState extends AgentData = AgentData> extends B
|
|
|
69
69
|
protected validateAgents(agents: BaseAgentLike<TState>[]): void;
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
-
export type
|
|
72
|
+
export type ConditionalWorkflowConstructProperties<TState extends AgentData> = Pick<ConditionalWorkflow<TState>, "agents" | "condition">;
|
|
@@ -26,7 +26,7 @@ export type LoopDecider<TState extends AgentData = AgentData> = (state: AgentGra
|
|
|
26
26
|
* @since 5.1
|
|
27
27
|
*/
|
|
28
28
|
export class LoopWorkflow<TState extends AgentData = AgentData> extends BaseWorkflow<TState> {
|
|
29
|
-
constructor(properties:
|
|
29
|
+
constructor(properties: LoopWorkflowConstructProperties<TState>);
|
|
30
30
|
/**
|
|
31
31
|
* Function that decides whether the loop should continue.
|
|
32
32
|
*
|
|
@@ -55,4 +55,4 @@ export class LoopWorkflow<TState extends AgentData = AgentData> extends BaseWork
|
|
|
55
55
|
protected isTerminalAgent(): boolean;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
export type
|
|
58
|
+
export type LoopWorkflowConstructProperties<TState extends AgentData> = Pick<LoopWorkflow<TState>, "decideContinue" | "workflow">;
|
|
@@ -20,7 +20,7 @@ import type { BaseWorkflow, WorkflowGenerateResult } from "./BaseWorkflow.js";
|
|
|
20
20
|
* @since 5.1
|
|
21
21
|
*/
|
|
22
22
|
export class ParallelWorkflow<TState extends AgentData = AgentData> extends BaseWorkflow<TState> {
|
|
23
|
-
constructor(properties:
|
|
23
|
+
constructor(properties: ParallelWorkflowConstructProperties<TState>);
|
|
24
24
|
/**
|
|
25
25
|
* Agents to run in parallel from the same input snapshot.
|
|
26
26
|
*
|
|
@@ -65,4 +65,4 @@ export class ParallelWorkflow<TState extends AgentData = AgentData> extends Base
|
|
|
65
65
|
protected isTerminalAgent(_agents: BaseAgentLike<TState>[], _index: number): boolean;
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
export type
|
|
68
|
+
export type ParallelWorkflowConstructProperties<TState extends AgentData> = Pick<ParallelWorkflow<TState>, "agents">;
|
|
@@ -16,7 +16,7 @@ import type { BaseWorkflow } from "./BaseWorkflow.js";
|
|
|
16
16
|
* @since 5.1
|
|
17
17
|
*/
|
|
18
18
|
export class RouterWorkflow<TState extends AgentData = AgentData> extends BaseWorkflow<TState> {
|
|
19
|
-
constructor(properties:
|
|
19
|
+
constructor(properties: RouterWorkflowConstructProperties<TState>);
|
|
20
20
|
/**
|
|
21
21
|
* Mapping of route keys to destination agents.
|
|
22
22
|
*
|
|
@@ -60,4 +60,4 @@ export class RouterWorkflow<TState extends AgentData = AgentData> extends BaseWo
|
|
|
60
60
|
protected validateAgents(agents: BaseAgentLike<TState>[]): void;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
export type
|
|
63
|
+
export type RouterWorkflowConstructProperties<TState extends AgentData> = Pick<RouterWorkflow<TState>, "agentsMap" | "routerAgent" | "routerOutputKey">;
|
|
@@ -17,7 +17,7 @@ import type { AgentData, AgentGraphState, BaseAgentLike, GraphEdge } from "../ty
|
|
|
17
17
|
* @since 5.1
|
|
18
18
|
*/
|
|
19
19
|
export class SequentialWorkflow<TState extends AgentData = AgentData> extends BaseWorkflow<TState> {
|
|
20
|
-
constructor(properties:
|
|
20
|
+
constructor(properties: SequentialWorkflowConstructProperties<TState>);
|
|
21
21
|
/**
|
|
22
22
|
* A list of agents to execute in the specified order.
|
|
23
23
|
*
|
|
@@ -53,4 +53,4 @@ export class SequentialWorkflow<TState extends AgentData = AgentData> extends Ba
|
|
|
53
53
|
protected validateAgents(agents: BaseAgentLike<TState>[]): void;
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
export type
|
|
56
|
+
export type SequentialWorkflowConstructProperties<TState extends AgentData> = Pick<SequentialWorkflow<TState>, "agents">;
|
|
@@ -26,7 +26,7 @@ export type SwitchDecider<TState extends AgentData = AgentData> = (state: AgentG
|
|
|
26
26
|
* @since 5.1
|
|
27
27
|
*/
|
|
28
28
|
export class SwitchWorkflow<TState extends AgentData = AgentData> extends BaseWorkflow<TState> {
|
|
29
|
-
constructor(properties:
|
|
29
|
+
constructor(properties: SwitchWorkflowConstructProperties<TState>);
|
|
30
30
|
/**
|
|
31
31
|
* Mapping of keys to destination agents.
|
|
32
32
|
*
|
|
@@ -70,5 +70,5 @@ export class SwitchWorkflow<TState extends AgentData = AgentData> extends BaseWo
|
|
|
70
70
|
protected validateAgents(agents: BaseAgentLike<TState>[]): void;
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
-
export type
|
|
73
|
+
export type SwitchWorkflowConstructProperties<TState extends AgentData> = Partial<Pick<SwitchWorkflow<TState>, "defaultAgent">>
|
|
74
74
|
& Pick<SwitchWorkflow<TState>, "agentsMap" | "resolver">;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{b as i,c as a}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as s,z as e}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./YIMNOUTF.js";var t=class extends s{static{this.properties={agent:0,context:0}}#t;async getContext(){return i(this.context)?await this.context():this.context}load(){this.#t=a(this)}disconnectedCallback(){this.#t?.unregister(this.agent.id),super.disconnectedCallback()}};e("arcgis-assistant-agent",t);export{t as ArcgisAssistantAgent};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{a as u,b as g,c as S}from"./LODKJRS4.js";import a from"./L77BTGXY.js";import{b as m,c as f}from"./CVHJMR5X.js";import{u as p}from"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([{property:h,subclass:l},{watch:w},d])=>{var v=Object.defineProperty,y=Object.getOwnPropertyDescriptor,o=(t,e,s,r)=>{for(var i=r>1?void 0:r?y(e,s):e,a=t.length-1,c;a>=0;a--)(c=t[a])&&(i=(r?c(e,s,i):c(i))||i);return r&&i&&v(e,s,i),i},n=class extends d{constructor(t){super(t)}initialize(){this.addHandles(w(()=>[this.name,this.description,this.inputSchema,this.outputSchema,this.execute],()=>{this.generate()},{initial:!0,sync:!0}))}getSchemas(){return[this.inputSchema,this.outputSchema].filter(Boolean)}generate(){let t=m(this.getSchemas());this._set("workspace",t);let e=`${this.id}-execute`,s={[e]:this._invokeExecuteNode.bind(this)},r=[{from:e,decide:()=>{}}];this._set("createGraph",()=>f(s,r,t,{agent:this,entryNode:e,middlewares:this.middlewares}))}async _invokeExecuteNode(t,e){try{return this.outputSchema?await this._invokeStructured(t,e):await this._invokeUnstructured(t,e)}catch(s){if(p(s))throw s;let r=s instanceof Error?s.message:String(s);return u({outputMessage:r},"failed",r)}}async _invokeStructured(t,e){if(!this.outputSchema)throw new Error("Output schema is required for structured invocation.");let s=this._validateInputState(t),r=await this.execute(s,e);if(typeof r=="string")throw new Error("Expected execute function to return an object matching the output schema, but received a string.");return g(r,this.outputSchema,t.agentExecutionContext.messages)}async _invokeUnstructured(t,e){let s=this._validateInputState(t),r=await this.execute(s,e),i=typeof r=="string"?r:JSON.stringify(r),a=i.trim()||"FunctionAgent completed.";return u({outputMessage:i},"success",a)}_validateInputState(t){if(!this.inputSchema)return t;let e=this.inputSchema.safeParse(S(t,this.inputSchema));if(!e.success)throw new Error(`FunctionAgent input schema validation failed: ${e.error.message}`);return{...t,...e.data}}};o([h()],n.prototype,"inputSchema",2);o([h()],n.prototype,"outputSchema",2);o([h()],n.prototype,"execute",2);n=o([l("FunctionAgent")],n);return n},"core/accessorSupport/decorators","core/reactiveUtils",a)
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import"./YIMNOUTF.js";var e=`# ArcGIS Knowledge Agent \u2014 Action Summary
|
|
3
|
+
|
|
4
|
+
You are a Knowledge Graph assistant that has executed tool calls to answer a user request.
|
|
5
|
+
|
|
6
|
+
## Context
|
|
7
|
+
|
|
8
|
+
**Data model**
|
|
9
|
+
{dataModelSummary}
|
|
10
|
+
|
|
11
|
+
**Assigned task**
|
|
12
|
+
{assignedTask}
|
|
13
|
+
|
|
14
|
+
**User request**
|
|
15
|
+
{userRequest}
|
|
16
|
+
|
|
17
|
+
**Tool result**
|
|
18
|
+
{toolResult}
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Goal
|
|
23
|
+
|
|
24
|
+
Generate a concise, complete Markdown response using the tool results.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
## Priority Rules (Strict Order)
|
|
29
|
+
|
|
30
|
+
### 1. User Formatting Override (Highest Priority)
|
|
31
|
+
|
|
32
|
+
- If the user specifies a format (table, list, bullets, etc.):
|
|
33
|
+
- Use that format exactly
|
|
34
|
+
- Ignore ALL default formatting rules below
|
|
35
|
+
- Do NOT add summaries or extra sections unless requested
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
### 2. Default Output (When no override)
|
|
40
|
+
|
|
41
|
+
Produce:
|
|
42
|
+
|
|
43
|
+
- **Summary**: 1\u20132 sentences (no header, no bullets)
|
|
44
|
+
- **Results**: Minimal, well-formatted data
|
|
45
|
+
- **Note (optional)**:
|
|
46
|
+
- 1\u20132 italicized sentences describing tool limitations
|
|
47
|
+
|
|
48
|
+
#### Limits
|
|
49
|
+
|
|
50
|
+
- maxPreviewItems: 5
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
### 3. Output Constraints (Non-Negotiable)
|
|
55
|
+
|
|
56
|
+
- Output **valid Markdown only** (no JSON)
|
|
57
|
+
- Do NOT hallucinate data (entities, fields, counts, relationships)
|
|
58
|
+
- Do NOT include:
|
|
59
|
+
- reasoning
|
|
60
|
+
- classification labels
|
|
61
|
+
- follow-up questions
|
|
62
|
+
- next steps
|
|
63
|
+
- intro phrases (\u201CHere are\u2026\u201D)
|
|
64
|
+
- restating the question
|
|
65
|
+
- End immediately after the response
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
### 4. Data Handling Rules
|
|
70
|
+
|
|
71
|
+
- If results are empty \u2192 clearly state no results returned
|
|
72
|
+
- If insufficient data \u2192 state limitation, do NOT speculate
|
|
73
|
+
- Do NOT output:
|
|
74
|
+
- raw nested objects
|
|
75
|
+
- large arrays
|
|
76
|
+
- geometry
|
|
77
|
+
- Summarize complex structures
|
|
78
|
+
- Truncate long values with \`\u2026\`
|
|
79
|
+
- Show entities/relationships only once
|
|
80
|
+
- Use:
|
|
81
|
+
- \u201Centity\u201D (not node)
|
|
82
|
+
- \u201Crelationship\u201D (not edge)
|
|
83
|
+
- Hide \`globalid\` and \`objectid\` unless explicitly requested
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
### 5. Formatting Rules (Default Mode Only)
|
|
88
|
+
|
|
89
|
+
- No headers; use _italic labels_ if needed
|
|
90
|
+
- Use:
|
|
91
|
+
- bullets \u2192 single item summaries
|
|
92
|
+
- tables \u2192 multiple results (limit to 5 rows)
|
|
93
|
+
- Reduce columns to key fields only
|
|
94
|
+
- Format:
|
|
95
|
+
- dates \u2192 \u201Cday month year\u201D
|
|
96
|
+
- time separate from date
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
### 6. Result-Type Formatting
|
|
101
|
+
|
|
102
|
+
**SEARCH_HITS**
|
|
103
|
+
|
|
104
|
+
- Highlight top match (bullets)
|
|
105
|
+
- Table for remaining results
|
|
106
|
+
|
|
107
|
+
**ENTITIES**
|
|
108
|
+
|
|
109
|
+
- Group by type (if multiple)
|
|
110
|
+
- Show key properties only
|
|
111
|
+
|
|
112
|
+
**RELATIONSHIPS**
|
|
113
|
+
|
|
114
|
+
- Format: \`(entity) \u2014[relationship]\u2192 (entity)\`
|
|
115
|
+
|
|
116
|
+
**PATHS**
|
|
117
|
+
|
|
118
|
+
- Summary + 1-3 examples
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
## Internal Processing (Do NOT output)
|
|
123
|
+
|
|
124
|
+
Classify results into:
|
|
125
|
+
|
|
126
|
+
- SEARCH_HITS, ENTITIES, RELATIONSHIPS, PATHS
|
|
127
|
+
|
|
128
|
+
## Failure Handling
|
|
129
|
+
|
|
130
|
+
- If data is insufficient \u2192 clearly state limitation
|
|
131
|
+
- Never infer or fabricate missing information
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
`;export{e as default};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import"./YIMNOUTF.js";var e=`## Who you are
|
|
3
|
+
|
|
4
|
+
You are a map assistant embedded inside a GIS application. You have no knowledge of history, science, people, events, cooking, or anything outside of this map and its data. You only know what is described in the Map Context below.
|
|
5
|
+
|
|
6
|
+
If asked anything outside of that context, you simply don't have that information \u2014 respond naturally and redirect to something you _can_ help with, using specific layer and field names from the map context.
|
|
7
|
+
|
|
8
|
+
Example of how to handle unknown topics:
|
|
9
|
+
"I don't have information on that \u2014 I only know about this map. You could ask me to list all layers in the map, or capabilities of this assistant."
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Your capabilities
|
|
14
|
+
|
|
15
|
+
You can help users with:
|
|
16
|
+
|
|
17
|
+
- Listing the layers in this map
|
|
18
|
+
- Listing the fields in a specific layer (use the tool)
|
|
19
|
+
- Suggesting specific queries using actual layer and field names
|
|
20
|
+
- Summarizing what this map contains and what users can do with it
|
|
21
|
+
- Letting users know when a map-related action isn't supported (e.g. charts, tables), and that it may be added in the future
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Input
|
|
26
|
+
|
|
27
|
+
Assigned task:
|
|
28
|
+
{assignedTask}
|
|
29
|
+
|
|
30
|
+
Latest user request:
|
|
31
|
+
{userRequest}
|
|
32
|
+
|
|
33
|
+
Prior steps:
|
|
34
|
+
{priorSteps}
|
|
35
|
+
|
|
36
|
+
Use the assigned task as the primary instruction. The question will **not** be restated again here.
|
|
37
|
+
Use the latest user request as supporting context.
|
|
38
|
+
Use prior steps only to explain a previous result, failure, or likely next action.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## Map Context
|
|
43
|
+
|
|
44
|
+
{layerSummary}
|
|
45
|
+
|
|
46
|
+
## Available agents (capabilities)
|
|
47
|
+
|
|
48
|
+
{agents}
|
|
49
|
+
|
|
50
|
+
### Response Guidelines
|
|
51
|
+
|
|
52
|
+
When suggesting what users can ask, be SPECIFIC using actual layer names:
|
|
53
|
+
|
|
54
|
+
- "Show me water sources with elevation above 500"
|
|
55
|
+
- "Filter Protected Areas in Panama by protection level"
|
|
56
|
+
- "Zoom to Watershed Boundaries"
|
|
57
|
+
|
|
58
|
+
For "what can I ask" responses, provide 3-5 specific example queries using fields from the context.
|
|
59
|
+
|
|
60
|
+
For off-topic questions:
|
|
61
|
+
"I can only help with this map. Try asking me to filter [LayerName] by [FieldName], or zoom to a location."
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Format
|
|
66
|
+
|
|
67
|
+
- Keep responses concise
|
|
68
|
+
- Use bullet points for lists
|
|
69
|
+
- Use new lines (\\n) and appropriate formatting in your response
|
|
70
|
+
- Use actual layer and field names from the map context in any suggestions
|
|
71
|
+
`;export{e as default};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{Ra as i}from"./IKEF7ZHH.js";async function n(a,t,e){if(e===void 0)throw new Error(["Unable to dispatch a custom event without a parent run id.",'"dispatchCustomEvent" can only be called from within an existing run (e.g.,',"inside a tool or a RunnableLambda).",`
|
|
3
|
+
|
|
4
|
+
If you continue to see this error, please import from "@langchain/core/callbacks/dispatch/web"`,"and explicitly pass in a config parameter.",`
|
|
5
|
+
|
|
6
|
+
Or, if you are calling this from a custom tool, ensure you're using the "tool" helper constructor as documented here:`,`
|
|
7
|
+
|`,`
|
|
8
|
+
\u2514-> https://js.langchain.com/docs/how_to/custom_tools#tool-function`,`
|
|
9
|
+
`].join(" "));let o=await i(e),s=o?.getParentRunId();o!==void 0&&s!==void 0&&await o.handleCustomEvent?.(a,t,s)}var u=async(a,t)=>{await n("trace_message",a,t)},m=async(a,t)=>{await n("graph_ux_suggestion",a,t)};export{u as a,m as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{g as t,h as e,t as i,u as a,v as n,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./YIMNOUTF.js";export default $arcgis.t(([l,{when:o,watch:c}])=>{var h=t`.messages-container{display:flex;flex:1;flex-direction:column;line-height:var(--calcite-font-line-height-relative-snug)}.messages-list{padding:var(--calcite-spacing-lg);display:flex;flex-direction:column;gap:var(--calcite-spacing-xxl);flex:1 1 auto;min-height:0;justify-content:flex-end;overflow:auto}.end-ref{margin-top:var(--calcite-spacing-lg)}`,s=class extends n{constructor(){super(...arguments),this.#t=i(),this.#s=!1,this.loading=!1,this.messages=new l([]),this.interrupt=null}static{this.properties={loading:5,messages:0,interrupt:0}}static{this.styles=h}#t;#s;firstUpdated(){this.#e()}loaded(){this.manager.onLifecycle(()=>[this.messages.on("change",()=>{this.#e()}),o(()=>!this.loading,()=>{this.#s=!1}),c(()=>[this.loading,this.interrupt],()=>this.#e())])}#e(){requestAnimationFrame(()=>{this.#s||this.#t.value?.scrollIntoView({behavior:"smooth",block:"end"})})}#i(){this.#s=!0}render(){return e`<div class="messages-container" @wheel=${this.#i}><div class="messages-list"><slot name=message-starter></slot><slot name=messages></slot><slot name=message-loading></slot></div><div class="end-ref" ${a(this.#t)}></div></div>`}};r("arcgis-assistant-chat",s);return s},"core/Collection","core/reactiveUtils")
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
-
import{
|
|
2
|
+
import{c as r}from"./NXKKG5TK.js";function s(e,n){return n?typeof n=="string"?l(e,n)??null:n:r(e,"arcgis-map")??null}function c(e,n){return n?typeof n=="string"?l(e,n)??null:n:r(e,"arcgis-link-chart")??r(e,"arcgis-map")??null}function l(e,n){let i=n.includes("#")||n.includes(".")||n.includes("["),t=e.getRootNode();return(i?void 0:t.querySelector(`#${n}`))??t.querySelector(n)??void 0}export{s as a,c as b};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import{D as Je,M as Ve,Q as Tt,a as rt,b as S,f as $,j,k as F,la as ee,ma as Ze,na as W,oa as bt,qa as ve,ra as fe,sa as Ce,t as st,ta as _t,u as at}from"./CJIV4KJZ.js";import{Ba as ze,D as $e,Db as q,Eb as Te,Gb as gt,Jb as be,Lb as wt,Ob as a,P as M,Pa as We,Qb as He,Sa as H,Sb as _e,Ta as de,U as it,Va as ct,Wa as dt,Wb as me,Xb as Z,Ya as Fe,Z as w,_a as ut,_b as ae,aa as Ue,ac as xe,ja as K,jb as ue,kb as ye,na as Be,nb as Me,nc as Ge,oa as B,pc as yt,rb as ft,tb as pt,tc as Mt,ua as lt,ub as Q,vb as ht}from"./IKEF7ZHH.js";import{Dd as z,s as mt}from"./ZEYIBYSF.js";var Ye=Symbol.for("AgentMiddleware");function A(e){return{[Ye]:!0,name:e.name,stateSchema:e.stateSchema,contextSchema:e.contextSchema,wrapToolCall:e.wrapToolCall,wrapModelCall:e.wrapModelCall,beforeAgent:e.beforeAgent,beforeModel:e.beforeModel,afterModel:e.afterModel,afterAgent:e.afterAgent,tools:e.tools}}var Se=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},ke=class extends Error{toolNames;constructor(e){super(`The model has called multiple tools: ${e.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`),this.toolNames=e}},Ke=class extends Error{toolName;errors;constructor(e,t){super(`Failed to parse structured output for tool '${e}':${t.map(n=>`
|
|
3
|
+
- ${n}`).join("")}.`),this.toolName=e,this.errors=t}},Ee=class extends Error{toolCall;toolError;constructor(e,t){let n=e instanceof Error?e:new Error(String(e)),o=JSON.stringify(t.args);super(`Error invoking tool '${t.name}' with kwargs ${o} with error: ${n.stack}
|
|
4
|
+
Please fix the error and try again.`),this.toolCall=t,this.toolError=n}},pe=class xt extends Error{static"~brand"="MiddlewareError";constructor(t,n){let o=t instanceof Error?t.message:String(t);super(o),this.name=t instanceof Error?t.name:`${n[0].toUpperCase()+n.slice(1)}Error`,t instanceof Error&&(this.cause=t)}static wrap(t,n){return st(t)?t:new xt(t,n)}static isInstance(t){return t instanceof Error&&"~brand"in t&&t["~brand"]==="MiddlewareError"}};function he(e){return"invoke"in e&&typeof e.invoke=="function"&&"_streamResponseChunks"in e}function ie(e){return typeof e=="object"&&e!=null&&"_queuedMethodOperations"in e&&"_getModelInstance"in e&&typeof e._getModelInstance=="function"}var vt=!0,ao=0,J=class qe{constructor(t,n,o){this.schema=t,this.tool=n,this.options=o}get name(){return this.tool.function.name}static fromSchema(t,n){function o(s){return s??`extract-${++ao}`}if(ue(t)||Me(t)){let s=_e(t);return new qe(s,{type:"function",function:{name:o(s.title),strict:!1,description:s.description??"Tool for extracting structured output from the model's response.",parameters:s}},n)}let r;return typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?r=t:r={name:o(t.title),description:t.description??"",parameters:t.schema||t},new qe(_e(t),{type:"function",function:r},n)}parse(t){let n=new He(this.schema).validate(t);if(!n.valid)throw new Ke(this.name,n.errors.map(o=>o.error));return t}},te=class Ct{_schemaType;schema;strict;constructor(t,n){if("schema"in t&&typeof t.schema=="object"&&t.schema!==null&&!("type"in t)){let o=t;this.schema=o.schema,this.strict=o.strict??vt}else this.schema=t,this.strict=n??vt}static fromSchema(t,n){return new Ct(_e(t),n)}parse(t){let n;if(typeof t.content=="string")n=t.content;else if(Array.isArray(t.content)){for(let o of t.content)if(typeof o=="object"&&o!==null&&"type"in o&&o.type==="text"&&"text"in o&&typeof o.text=="string"){n=o.text;break}}if(!(!n||n===""))try{let o=JSON.parse(n);return new He(this.schema).validate(o).valid?o:void 0}catch{}}};function St(e,t,n){if(!e)return[];if(typeof e=="object"&&e!==null&&"__responseFormatUndefined"in e)return[];if(Array.isArray(e)){if(e.every(r=>r instanceof J||r instanceof te))return e;if(e.every(r=>ue(r)))return e.map(r=>J.fromSchema(r,t));if(e.every(r=>q(r)))return e.map(r=>J.fromSchema(r,t));if(e.every(r=>typeof r=="object"&&r!==null&&!q(r)&&!ue(r)))return e.map(r=>J.fromSchema(r,t));throw new Error(`Invalid response format: list contains mixed types.
|
|
5
|
+
All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(e instanceof J||e instanceof te)return[e];let o=io(n);if(ue(e))return o?[te.fromSchema(e)]:[J.fromSchema(e,t)];if(q(e))return o?[te.fromSchema(e)]:[J.fromSchema(e,t)];if(typeof e=="object"&&e!==null&&"properties"in e)return o?[te.fromSchema(e)]:[J.fromSchema(e,t)];throw new Error(`Invalid response format: ${String(e)}`)}function io(e){return!e||!he(e)||!("profile"in e)||typeof e.profile!="object"||!e.profile?!1:"structuredOutput"in e.profile&&e.profile.structuredOutput===!0}var Xe=Symbol.for("langgraph-zod");Xe in globalThis||(globalThis[Xe]=new WeakSet);function kt(e){let t=globalThis[Xe];t.has(e)||(Object.defineProperty(e,"langgraph",{get(){let n=this;return{metadata(o){return Ce(n,{jsonSchemaExtra:o})},reducer(o,r){return Ce(n,{default:be(n),reducer:{schema:r,fn:o}})}}}}),t.add(e))}try{kt(a.ZodType.prototype),kt(z.ZodType.prototype)}catch(e){throw new Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:e})}var Et=class extends mt{constructor(e){super(),this.parent=e,this._map=this.parent._map}add(e,...t){let n=t[0];if(n&&!n?.default){let o=be(e);o!=null&&(n.default=o)}return super.add(e,...t)}},lo=new Et(fe);function It(e=!0,t,n=[]){let o={jumpTo:new Ze},r={},s={},i=l=>{if(W.isInstance(l)){for(let[c,d]of Object.entries(l.fields))if(!(c in o)){if(o[c]=d,c.startsWith("_"))continue;ee.isInstance(d)?(r[c]=d.inputSchema||d.valueSchema,s[c]=d.valueSchema):(r[c]=d,s[c]=d)}return}let u=Te(l);for(let[c,d]of Object.entries(u)){let g=c.startsWith("_");if(!(c in o)){if(ye(d)){let p=fe.get(d);if(p?.reducer){p.reducer.schema?(o[c]=new ee(d,{inputSchema:p.reducer.schema,reducer:p.reducer.fn}),g||(r[c]=p.reducer.schema,s[c]=d)):(o[c]=new ee(d,{reducer:p.reducer.fn}),g||(r[c]=d,s[c]=d));continue}}o[c]=d,g||(r[c]=d,s[c]=d)}}};t&&(W.isInstance(t)||q(t))&&i(t);for(let l of n)l.stateSchema&&(W.isInstance(l.stateSchema)||q(l.stateSchema))&&i(l.stateSchema);return e&&(s.structuredResponse=new Ze),{state:new W({messages:ve,...o}),input:new W({messages:ve,...r}),output:new W({messages:ve,...s})}}var Qe=/<name>(.*?)<\/name>/s,et=/<content>(.*?)<\/content>/s;function co(e,t){if(W.isInstance(e)){let n={};for(let o of Object.keys(e.fields))o in t&&(n[o]=t[o]);return n}if(Me(e))return Q(e,t);throw new Error(`Invalid state schema type: ${typeof e}`)}function Rt(e){if(!w.isInstance(e)||Ue.isInstance(e)||!e.name)return e;let{name:t}=e;if(typeof e.content=="string")return new w({...e.lc_kwargs,content:`<name>${t}</name><content>${e.content}</content>`,name:void 0});let n=[],o=0;for(let r of e.content)typeof r=="string"?(o+=1,n.push(`<name>${t}</name><content>${r}</content>`)):typeof r=="object"&&"type"in r&&r.type==="text"?(o+=1,n.push({...r,text:`<name>${t}</name><content>${r.text}</content>`})):n.push(r);return o||n.unshift({type:"text",text:`<name>${t}</name><content></content>`}),new w({...e.lc_kwargs,content:n,name:void 0})}function Ot(e){if(!w.isInstance(e)||!e.content)return e;let t=[],n;if(Array.isArray(e.content))t=e.content.filter(o=>{if(o.type==="text"&&typeof o.text=="string"){let r=o.text.match(Qe),s=o.text.match(et);return r&&(!s||s[1]==="")?(n=r[1],!1):!0}return!0}).map(o=>{if(o.type==="text"&&typeof o.text=="string"){let r=o.text.match(Qe),s=o.text.match(et);return!r||!s?o:(n=r[1],{...o,text:s[1]})}return o});else{let o=e.content,r=o.match(Qe),s=o.match(et);if(!r||!s)return e;n=r[1],t=s[1]}return new w({...Object.keys(e.lc_kwargs??{}).length>0?e.lc_kwargs:e,content:t,name:n})}function re(e){return me.isRunnable(e)}function At(e){return he(e)?"bindTools"in e&&typeof e.bindTools=="function":!1}var tt=(e,t,n={})=>{if(At(e))return e.bindTools(t,n);if(Z.isRunnableBinding(e)&&At(e.bound)){let o=e.bound.bindTools(t,n);return Z.isRunnableBinding(o)?new Z({bound:o.bound,config:{...e.config,...o.config},kwargs:{...e.kwargs,...o.kwargs},configFactories:o.configFactories??e.configFactories}):new Z({bound:o,config:e.config,kwargs:e.kwargs,configFactories:e.configFactories})}return null};function Ie(e){if(typeof e=="function")return;let t=e;if(ae.isRunnableSequence(t)&&(t=t.steps.find(n=>Z.isRunnableBinding(n))||t),!ie(t)){if(Z.isRunnableBinding(t)){let n=t.kwargs!=null&&typeof t.kwargs=="object"&&"tools"in t.kwargs&&Array.isArray(t.kwargs.tools)&&t.kwargs.tools.length>0,o=t.config!=null&&typeof t.config=="object"&&"tools"in t.config&&Array.isArray(t.config.tools)&&t.config.tools.length>0;if(n||o)throw new Se}if("tools"in t&&t.tools!==void 0&&Array.isArray(t.tools)&&t.tools.length>0)throw new Se}}function le(e){return!!(w.isInstance(e)&&e.tool_calls&&e.tool_calls.length>0)}function Nt(e){if(e==null)return new B("");if(B.isInstance(e))return e;if(typeof e=="string")return new B({content:[{type:"text",text:e}]});throw new Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof e}`)}async function jt(e,t,n={}){let o=tt(e,t,n);if(o)return o;if(ie(e)){let r=tt(await e._getModelInstance(),t,n);if(r)return r}if(ae.isRunnableSequence(e)){let r=e.steps.findIndex(s=>Z.isRunnableBinding(s)||he(s)||ie(s));if(r>=0){let s=tt(e.steps[r],t,n);if(s){let i=e.steps.slice();return i.splice(r,1,s),ae.from(i)}}}throw new Error(`llm ${e} must define bindTools method.`)}function uo(e){if(e.length===0)return;if(e.length===1)return e[0];function t(o,r){return async(s,i)=>o(s,async u=>r(u,i))}let n=e[e.length-1];for(let o=e.length-2;o>=0;o--)n=t(e[o],n);return n}function Pt(e){let t=e.filter(n=>n.wrapToolCall);if(t.length!==0)return uo(t.map(n=>{let o=n.wrapToolCall;return async(s,i)=>{let l=s.state,u=async c=>{let d={...l,...c.state};return i({...c,state:d})};try{let c=await o({...s,state:{messages:l.messages,...n.stateSchema?co(n.stateSchema,{...l}):{}}},u);if(!M.isInstance(c)&&!F(c))throw new Error(`Invalid response from "wrapToolCall" in middleware "${n.name}": expected ToolMessage or Command, got ${typeof c}`);return c}catch(c){throw pe.wrap(c,n.name)}}}))}async function Lt(e,t){let n={};for(let o of e){if(!o.stateSchema)continue;let r=o.stateSchema;if(W.isInstance(o.stateSchema)){let l={};for(let[u,c]of Object.entries(o.stateSchema.fields))ee.isInstance(c)?l[u]=c.inputSchema||c.valueSchema:l[u]=c;r=z.object(l)}let s=await ft(wt(r,l=>l.startsWith("_")),t);if(s.success){Object.assign(n,s.data);continue}let i=s.error.issues.filter(l=>l.code==="invalid_type").map(l=>` - ${l.path.join(".")}: Required`).join(`
|
|
6
|
+
`);throw new Error(`Middleware "${o.name}" has required state fields that must be initialized:
|
|
7
|
+
${i}
|
|
8
|
+
|
|
9
|
+
To fix this, either:
|
|
10
|
+
1. Provide default values in your middleware's state schema using .default():
|
|
11
|
+
stateSchema: z.object({
|
|
12
|
+
myField: z.string().default("default value")
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
2. Or make the fields optional using .optional():
|
|
16
|
+
stateSchema: z.object({
|
|
17
|
+
myField: z.string().optional()
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
3. Or ensure you pass these values when invoking the agent:
|
|
21
|
+
agent.invoke({
|
|
22
|
+
messages: [...],
|
|
23
|
+
${s.error.issues[0]?.path.join(".")}: "value"
|
|
24
|
+
})`)}return n}function Dt(e){let t={messages:z.custom(()=>[]),structuredResponse:z.any().optional()};if(!e)return z.object(t);let n;if(W.isInstance(e)){n={};for(let[r,s]of Object.entries(e.fields))ee.isInstance(s)?n[r]=s.inputSchema||s.valueSchema:n[r]=s}else n=Te(e);let o={...t};for(let[r,s]of Object.entries(n))r.startsWith("_")?o[r]=s.optional():o[r]=s;return z.object(o)}function $t(e){if(q(e))return gt(e);if(W.isInstance(e)){let t={};for(let[n,o]of Object.entries(e.fields)){let r;ee.isInstance(o)?r=o.inputSchema||o.valueSchema:r=o,t[n]=ye(r)?r.optional():z.any().optional()}return z.object(t)}return z.object({})}function G(e){if(e){if(["model_request","tools",S].includes(e))return e;if(e==="model")return"model_request";if(e==="tools")return"tools";if(e==="end")return S;throw new Error(`Invalid jump target: ${e}, must be "model", "tools" or "end".`)}}function Ae(...e){return AbortSignal.any(e.filter(t=>t!=null&&typeof t=="object"&&"aborted"in t&&typeof t.aborted=="boolean"))}var Oe={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},google:{package:"@langchain/google",className:"ChatGoogle"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},aws:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},fireworks:{package:"@langchain/fireworks",className:"ChatFireworks"},together:{package:"@langchain/together-ai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/perplexity",className:"ChatPerplexity"}},Bt=Object.keys(Oe);async function fo(e,t){let n;if(t)n=Oe[t];else{let o=Object.entries(Oe).find(([,r])=>r.className===e);n=o?o[1]:void 0}if(n)try{return(await import(n.package))[n.className]}catch(o){let r=o;if("code"in r&&r.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in r&&typeof r.message=="string"){let s=(r.message.startsWith("Error: ")?r.message.slice(7):r.message).split("Cannot find package '")[1].split("'")[0];throw new Error(`Unable to import ${s}. Please install with \`npm install ${s}\` or \`pnpm install ${s}\``)}throw o}}async function po(e,t,n={}){let o=t||ho(e);if(!o)throw new Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let r=Oe[o];if(!r){let l=Bt.join(", ");throw new Error(`Unsupported { modelProvider: ${o} }.
|
|
25
|
+
|
|
26
|
+
Supported model providers are: ${l}`)}let{modelProvider:s,...i}=n;return new(await fo(r.className,o))({model:e,...i})}function ho(e){return e.startsWith("gpt-3")||e.startsWith("gpt-4")||e.startsWith("gpt-5")||e.startsWith("o1")||e.startsWith("o3")||e.startsWith("o4")?"openai":e.startsWith("claude")?"anthropic":e.startsWith("command")?"cohere":e.startsWith("accounts/fireworks")?"fireworks":e.startsWith("gemini")?"google-vertexai":e.startsWith("amazon.")?"bedrock":e.startsWith("mistral")?"mistralai":e.startsWith("sonar")||e.startsWith("pplx")?"perplexity":void 0}var Ut=class Re extends Ve{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(t){super(t),this._defaultConfig=t.defaultConfig??{},t.configurableFields==="any"?this._configurableFields="any":this._configurableFields=t.configurableFields??["model","modelProvider"],t.configPrefix?this._configPrefix=t.configPrefix.endsWith("_")?t.configPrefix:`${t.configPrefix}_`:this._configPrefix="",this._queuedMethodOperations=t.queuedMethodOperations??this._queuedMethodOperations,this._profile=t.profile??void 0,this.metadata={...this.metadata,ls_integration:"langchain_init_chat_model"}}async _getModelInstance(t){let n=this._getCacheKey(t),o=this._modelInstanceCache.get(n);if(o)return o;let r={...this._defaultConfig,...this._modelParams(t)},s=await po(r.model,r.modelProvider,r);for(let[i,l]of Object.entries(this._queuedMethodOperations))i in s&&typeof s[i]=="function"&&(s=await s[i](...l));return this._modelInstanceCache.set(n,s),s}async _generate(t,n,o){return(await this._getModelInstance(n))._generate(t,n??{},o)}bindTools(t,n){let o={...this._queuedMethodOperations};return o.bindTools=[t,n],new Re({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:o})}withStructuredOutput=(t,...n)=>{let o={...this._queuedMethodOperations};return o.withStructuredOutput=[t,...n],new Re({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:o})};_modelParams(t){let n=t?.configurable??{},o={};for(let[r,s]of Object.entries(n))if(r.startsWith(this._configPrefix)){let i=this._removePrefix(r,this._configPrefix);o[i]=s}return this._configurableFields!=="any"&&(o=Object.fromEntries(Object.entries(o).filter(([r])=>this._configurableFields.includes(r)))),o}_removePrefix(t,n){return t.startsWith(n)?t.slice(n.length):t}withConfig(t){let n={...t||{}},o=this._modelParams(n),r=Object.fromEntries(Object.entries(n).filter(([s])=>s!=="configurable"));return r.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([s])=>this._configPrefix&&!Object.keys(o).includes(this._removePrefix(s,this._configPrefix)))),new Z({config:n,bound:new Re({defaultConfig:{...this._defaultConfig,...o},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(t,n){let o=await this._getModelInstance(n),r=de(n);return o.invoke(t,r)}async stream(t,n){let o=new ut({generator:await(await this._getModelInstance(n)).stream(t,n),config:n});return await o.setup,Fe.fromAsyncGenerator(o)}async batch(t,n,o){return super.batch(t,n,o)}async*transform(t,n){let o=await this._getModelInstance(n),r=de(n);yield*o.transform(t,r)}async*streamLog(t,n,o){let r=await this._getModelInstance(n),s=de(n);yield*r.streamLog(t,s,{...o,_schemaFormat:"original",includeNames:o?.includeNames,includeTypes:o?.includeTypes,includeTags:o?.includeTags,excludeNames:o?.excludeNames,excludeTypes:o?.excludeTypes,excludeTags:o?.excludeTags})}streamEvents(t,n,o){let r=this;async function*s(){let i=await r._getModelInstance(n),l=de(n),u=i.streamEvents(t,l,o);for await(let c of u)yield c}return Fe.fromAsyncGenerator(s())}get profile(){if(this._profile)return this._profile;let t=this._getCacheKey({});return this._modelInstanceCache.get(t)?.profile??{}}_getCacheKey(t){let n=t??{};if(n.configurable){let{configurable:o}=n,r={};for(let[s,i]of Object.entries(o))s.startsWith("__pregel_")||(r[s]=i);n={...n,configurable:r}}return JSON.stringify(n)}};async function X(e,t){let{configurableFields:n,configPrefix:o,modelProvider:r,profile:s,...i}={configPrefix:"",...t??{}};if(r===void 0&&e?.includes(":")){let[d,...g]=e.split(":"),p=g.length===0?[d]:[d,g.join(":")];Bt.includes(p[0])&&([r,e]=p)}let l=Array.isArray(n)?[...n]:n;!e&&l===void 0&&(l=["model","modelProvider"]),o&&l===void 0&&console.warn(`{ configPrefix: ${o} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let u={...i},c;return l===void 0?c=new Ut({defaultConfig:{...u,model:e,modelProvider:r},configPrefix:o,profile:s}):(e&&(u.model=e),r&&(u.modelProvider=r),c=new Ut({defaultConfig:u,configPrefix:o,configurableFields:l,profile:s})),await c._getModelInstance(),c}var ce=class extends me{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#e;constructor(e){super(),this.name=e.name??e.func.name,this.func=e.func,this.config=e.tags?{tags:e.tags}:void 0,this.recurse=e.recurse??this.recurse}getState(){return this.#e}setState(e){this.#e={...this.#e,...e}}async invoke(e,t){let n=H(this.config,t),o=await We.runWithConfig(n,async()=>this.func(e,n));return me.isRunnable(o)&&this.recurse?await We.runWithConfig(n,async()=>o.invoke(e,n)):(this.#e=o,o)}};function zt(e,t){let n,o;if(t==="inline")n=Rt,o=Ot;else throw new Error(`Invalid agent name mode: ${t}. Needs to be one of: "inline"`);function r(s){return s.map(n)}return ae.from([xe.from(r),e,xe.from(o)])}function go(e){return w.isInstance(e)||F(e)||typeof e=="object"&&e!==null&&"structuredResponse"in e&&"messages"in e}var O="model_request",Wt=class extends ce{#e;#o;constructor(e){super({name:e.name??"model",func:(t,n)=>this.#t(t,n)}),this.#e=e,this.#o=e.systemMessage}async#s(e,t=this.#e.responseFormat){if(!t)return;let n;ie(e)?n=await e._getModelInstance():typeof e!="string"&&(n=e);let o=St(t,void 0,n);if(o.length!==0)return o.every(r=>r instanceof te)?{type:"native",strategy:o[0]}:{type:"tool",tools:o.filter(r=>r instanceof J).reduce((r,s)=>(r[s.name]=s,r),{})}}async#t(e,t){let n=e.messages.at(-1);if(n&&M.isInstance(n)&&n.name&&this.#e.shouldReturnDirect.has(n.name))return[new j({update:{messages:[]}})];let{response:o,lastAiMessage:r,collectedCommands:s}=await this.#a(e,t);if(typeof o=="object"&&o!==null&&"structuredResponse"in o&&"messages"in o){let{structuredResponse:u,messages:c}=o;return{messages:[...e.messages,...c],structuredResponse:u}}let i=[],l=w.isInstance(o)?o:r;return l&&(l.name=this.name,l.lc_kwargs.name=this.name,this.#r(e,l)?i.push(new j({update:{messages:[new w({content:"Sorry, need more steps to process this request.",name:this.name,id:l.id})]}})):i.push(new j({update:{messages:[l]}}))),F(o)&&!s.includes(o)&&i.push(o),i.push(...s),i}#n(){if(typeof this.#e.model=="string")return X(this.#e.model);if(this.#e.model)return this.#e.model;throw new Error("No model option was provided, either via `model` option.")}async#a(e,t,n={}){let o=await this.#n(),r=t,s=this.#o,i=null,l=[],u=async p=>{Ie(p.model);let h=await this.#s(p.model,p.responseFormat),I=await this.#d(p.model,p,h),V=[...s.text===""?[]:[s],...p.messages],k=Ae(this.#e.signal,t.signal),T=await dt(I.invoke(V,{...t,signal:k}),k);if(i=T,h?.type==="native"){let D=h.strategy.parse(T);return D?{structuredResponse:D,messages:[T]}:T}if(!h||!T.tool_calls)return T;let L=T.tool_calls.filter(D=>D.name in h.tools);if(L.length===0)return T;if(L.length>1)return this.#l(T,L,h);let R=h.tools[L[0].name]?.options?.toolMessageContent;return this.#c(T,L[0],h,R??n.lastMessage)},c=this.#e.wrapModelCallHookMiddleware??[],d=u;for(let p=c.length-1;p>=0;p--){let[h,I]=c[p];if(h.wrapModelCall){let V=d,k=h,T=I;d=async L=>{let R=s,D=k.contextSchema?Q(k.contextSchema,r?.context||{}):r?.context,se=Object.freeze({context:D,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal}),U={...L,state:{...h.stateSchema?Q($t(h.stateSchema),e):{},...T(),messages:e.messages},runtime:se},E=async x=>{s=R;let m=x.tools??[],y=new Map(this.#e.toolClasses.filter(re).map(N=>[N.name,N])),v=m.filter(N=>re(N)&&!y.has(N.name)),_=m.filter(N=>{if(!re(N))return!1;let nt=y.get(N.name);return nt!=null&&nt!==N});if(v.length>0&&!this.#e.middleware?.some(N=>N.wrapToolCall!=null))throw new Error(`You have added a new tool in "wrapModelCall" hook of middleware "${k.name}": ${v.map(N=>N.name).join(", ")}. This is not supported unless a middleware provides a "wrapToolCall" handler to execute it.`);if(_.length>0)throw new Error(`You have modified a tool in "wrapModelCall" hook of middleware "${k.name}": ${_.map(N=>N.name).join(", ")}. This is not supported.`);let C=x,f=x.systemPrompt!==s.text,b=x.systemMessage!==s;if(f&&b)throw new Error("Cannot change both systemPrompt and systemMessage in the same request.");f&&(s=new B({content:[{type:"text",text:x.systemPrompt}]}),C={...x,systemPrompt:s.text,systemMessage:s}),b&&(s=new B({...x.systemMessage}),C={...x,systemPrompt:s.text,systemMessage:s});let we=await V(C);return F(we)&&i?(l.includes(we)||l.push(we),i):we};if(!k.wrapModelCall)return E(U);try{let x=await k.wrapModelCall(U,E);if(!go(x))throw new Error(`Invalid response from "wrapModelCall" in middleware "${k.name}": expected AIMessage or Command, got ${typeof x}`);return w.isInstance(x)?i=x:F(x)&&l.push(x),x}catch(x){throw pe.wrap(x,k.name)}}}}s=this.#o;let g={model:o,responseFormat:this.#e.responseFormat,systemPrompt:s?.text,systemMessage:s,messages:e.messages,tools:this.#e.toolClasses,state:e,runtime:Object.freeze({context:r?.context,store:r.store,configurable:r.configurable,writer:r.writer,interrupt:r.interrupt,signal:r.signal})};return{response:await d(g),lastAiMessage:i,collectedCommands:l}}#l(e,t,n){let o=new ke(t.map(r=>r.name));return this.#i(o,e,t[0],n)}#c(e,t,n,o){let r=n.tools[t.name];try{let s=r.parse(t.args);return{structuredResponse:s,messages:[e,new M({tool_call_id:t.id??"",content:JSON.stringify(s),name:t.name}),new w(o??`Returning structured response: ${JSON.stringify(s)}`)]}}catch(s){return this.#i(s,e,t,n)}}async#i(e,t,n,o){let r=Object.values(o.tools).at(0)?.options?.handleError,s=n.id;if(!s)throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(r===!1)throw e;if(r===void 0||typeof r=="boolean"&&r||Array.isArray(r)&&r.some(i=>i instanceof ke))return new j({update:{messages:[t,new M({content:e.message,tool_call_id:s})]},goto:O});if(typeof r=="string")return new j({update:{messages:[t,new M({content:r,tool_call_id:s})]},goto:O});if(typeof r=="function"){let i=await r(e);if(typeof i!="string")throw new Error("Error handler must return a string.");return new j({update:{messages:[t,new M({content:i,tool_call_id:s})]},goto:O})}return new j({update:{messages:[t,new M({content:e.message,tool_call_id:s})]},goto:O})}#r(e,t){let n=w.isInstance(t)&&t.tool_calls?.every(r=>this.#e.shouldReturnDirect.has(r.name)),o="remainingSteps"in e?e.remainingSteps:void 0;return!!(o&&(o<1&&n||o<2&&le(e.messages.at(-1))))}async#d(e,t,n){let o={},r=Object.values(n&&"tools"in n?n.tools:{}),s=[...t?.tools??this.#e.toolClasses,...r.map(u=>u.tool)],i=t?.toolChoice||(r.length>0?"any":void 0);if(n?.type==="native"){let u=t?.modelSettings?.strict??n?.strategy?.strict??!0,c={name:n.strategy.schema?.name??"extract",description:ht(n.strategy.schema),schema:n.strategy.schema,strict:u};Object.assign(o,{response_format:{type:"json_schema",json_schema:c},outputConfig:{format:{type:"json_schema",schema:n.strategy.schema}},responseSchema:n.strategy.schema,ls_structured_output_format:{kwargs:{method:"json_schema"},schema:n.strategy.schema},strict:u})}let l=await jt(e,s,{...o,...t?.modelSettings,tool_choice:i});return this.#e.includeAgentName==="inline"?zt(l,this.#e.includeAgentName):l}getState(){let e=super.getState();return{messages:[],...e&&!F(e)?e:{}}}};var Ft=(e,t)=>`Error: ${e} is not a valid tool, try one of [${t.join(", ")}].`,P="tools",Ht=e=>Array.isArray(e)&&e.every($e.isInstance),wo=e=>typeof e=="object"&&e!=null&&"messages"in e&&Ht(e.messages),yo=e=>typeof e=="object"&&e!=null&&"lg_tool_call"in e;function Mo(e,t){return e instanceof Ee?new M({content:e.message,tool_call_id:t.id,name:t.name}):new M({content:`${e}
|
|
27
|
+
Please fix your mistakes.`,tool_call_id:t.id,name:t.name})}var Jt=class extends ce{tools;trace=!1;signal;handleToolErrors=Mo;wrapToolCall;constructor(e,t){let{name:n,tags:o,handleToolErrors:r,signal:s,wrapToolCall:i}=t??{};super({name:n,tags:o,func:(l,u)=>this.run(l,u)}),this.options=t,this.tools=e,this.handleToolErrors=r??this.handleToolErrors,this.signal=s,this.wrapToolCall=i}#e(e,t,n){if(at(e)||this.signal?.aborted||n&&this.handleToolErrors!==!0||!this.handleToolErrors)throw e;if(typeof this.handleToolErrors=="function"){let o=this.handleToolErrors(e,t);if(o&&M.isInstance(o))return o;throw e}else if(this.handleToolErrors)return new M({name:t.name,content:`${e}
|
|
28
|
+
Please fix your mistakes.`,tool_call_id:t.id});throw e}async runTool(e,t,n){let o=t,r={context:o?.context,store:o?.store,configurable:o?.configurable,writer:o?.writer,interrupt:o?.interrupt,signal:o?.signal},s=this.tools.find(u=>u.name===e.name),i=async u=>{let{toolCall:c,tool:d}=u,g=d??this.tools.find(h=>h.name===c.name);if(g===void 0){let h=this.tools.map(I=>I.name);return new M({content:Ft(c.name,h),tool_call_id:c.id,name:c.name,status:"error"})}let p=g;try{let h=await p.invoke({...c,type:"tool_call"},{...t,config:t,toolCallId:c.id,state:t.configurable?.__pregel_scratchpad?.currentTaskInput,signal:Ae(this.signal,t.signal)});return M.isInstance(h)||F(h)?h:new M({name:p.name,content:typeof h=="string"?h:JSON.stringify(h),tool_call_id:c.id})}catch(h){throw h instanceof it?new Ee(h,c):h}},l={toolCall:e,tool:s,state:n,runtime:r};if(this.wrapToolCall)try{return await this.wrapToolCall(l,i)}catch(u){return this.#e(u,e,!0)}if(!s){let u=this.tools.map(c=>c.name);return new M({content:Ft(e.name,u),tool_call_id:e.id,name:e.name,status:"error"})}try{return await i(l)}catch(u){return this.#e(u,e,!1)}}async run(e,t){let n;if(yo(e)){let{lg_tool_call:s,jumpTo:i,...l}=e;n=[await this.runTool(e.lg_tool_call,t,l)]}else{let s;if(Ht(e))s=e;else if(wo(e))s=e.messages;else throw new Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let i=new Set(s.filter(u=>u.getType()==="tool").map(u=>u.tool_call_id)),l;for(let u=s.length-1;u>=0;u-=1){let c=s[u];if(w.isInstance(c)){l=c;break}}if(!w.isInstance(l))throw new Error("ToolNode only accepts AIMessages as input.");n=await Promise.all(l.tool_calls?.filter(u=>u.id==null||!i.has(u.id)).map(u=>this.runTool(u,t,e))??[])}if(!n.some(F))return Array.isArray(e)?n:{messages:n};let o=[],r=null;for(let s of n)F(s)?s.graph===j.PARENT&&Array.isArray(s.goto)&&s.goto.every(i=>To(i))?r?r.goto.push(...s.goto):r=new j({graph:j.PARENT,goto:s.goto}):o.push(s):o.push(Array.isArray(e)?[s]:{messages:[s]});return r&&o.push(r),o}};function To(e){return e instanceof $}function Ne(e,t){let o=0;if(t&&t.length>0){let r=0;for(let s of t){let i=Mt(s)?Tt(s):s;r+=JSON.stringify(i).length}o+=r}for(let r of e){let s;typeof r.content=="string"?s=r.content:Array.isArray(r.content)?s=r.content.map(i=>typeof i=="string"?i:i.type==="text"&&"text"in i?i.text:"").join(""):s="",w.isInstance(r)&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0&&(s+=JSON.stringify(r.tool_calls)),M.isInstance(r)&&(s+=r.tool_call_id??""),o+=s.length}return Math.ceil(o/4)}function Y(e){if(!(!e||typeof e=="function"))return e.canJumpTo}function oe(e){return typeof e=="function"?e:e.hook}var bo=class{},_o=class{},ne=class extends ce{#e;constructor(e,t){super(e),this.#e=t}async invokeMiddleware(e,t){let n={};if(this.middleware.contextSchema){let u=this.middleware.contextSchema?.shape;if(u){let c={},d=t?.context||{};for(let g of Object.keys(u))g in d&&(c[g]=d[g]);n=Q(this.middleware.contextSchema,c)}}let o={...this.#e.getState(),...e,messages:e.messages},r={context:n,store:t?.store,configurable:t?.configurable,writer:t?.writer,interrupt:t?.interrupt,signal:t?.signal},s=await this.runHook(o,Object.freeze(Object.assign(new _o,{...r,context:Object.freeze(Object.assign(new bo,n))})));if(!s)return{jumpTo:void 0};let i,l;if(this.name?.startsWith("BeforeAgentNode_")?(i=Y(this.middleware.beforeAgent),l="beforeAgent.canJumpTo"):this.name?.startsWith("BeforeModelNode_")?(i=Y(this.middleware.beforeModel),l="beforeModel.canJumpTo"):this.name?.startsWith("AfterAgentNode_")?(i=Y(this.middleware.afterAgent),l="afterAgent.canJumpTo"):this.name?.startsWith("AfterModelNode_")&&(i=Y(this.middleware.afterModel),l="afterModel.canJumpTo"),typeof s.jumpTo=="string"&&!i?.includes(s.jumpTo)){let u=i&&i.length>0?`must be one of: ${i?.join(", ")}.`:l?`no ${l} defined in middleware ${this.middleware.name}`:"";throw new Error(`Invalid jump target: ${s.jumpTo}, ${u}.`)}if(typeof s=="object"&&"type"in s){if(s.type==="terminate"){if(s.error)throw s.error;return{...o,...s.result||{},jumpTo:s.jumpTo}}throw new Error(`Invalid control action: ${JSON.stringify(s)}`)}return{...o,...s,jumpTo:s.jumpTo}}get nodeOptions(){return{input:Dt(this.middleware.stateSchema)}}};var Gt=class extends ne{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(e,t){super({name:`BeforeAgentNode_${e.name}`,func:async(n,o)=>this.invokeMiddleware(n,o)},t),this.middleware=e}runHook(e,t){return oe(this.middleware.beforeAgent)(e,t)}};var Vt=class extends ne{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(e,t){super({name:`BeforeModelNode_${e.name}`,func:async(n,o)=>this.invokeMiddleware(n,o)},t),this.middleware=e}runHook(e,t){return oe(this.middleware.beforeModel)(e,t)}};var Zt=class extends ne{lc_namespace=["langchain","agents","afterModelNodes"];constructor(e,t){super({name:`AfterModelNode_${e.name}`,func:async(n,o)=>this.invokeMiddleware(n,o)},t),this.middleware=e}runHook(e,t){return oe(this.middleware.afterModel)(e,t)}};var Yt=class extends ne{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(e,t){super({name:`AfterAgentNode_${e.name}`,func:async(n,o)=>this.invokeMiddleware(n,o)},t),this.middleware=e}runHook(e,t){return oe(this.middleware.afterAgent)(e,t)}};var Kt=class{#e=new Map;addNode(e,t){this.#e.set(e.name,[...this.#e.get(e.name)??[],t])}getState(e){let t=(this.#e.get(e)??[]).reduce((n,o)=>({...n,...o.getState()??{}}),{});return delete t.jumpTo,t}};var qt=class Xt{#e;#o="v2";#s;#t=new Kt;#n;constructor(t,n){if(this.options=t,this.#n=H(n??{},{metadata:{ls_integration:"langchain_create_agent"}}),t.name&&(this.#n=H(this.#n,{metadata:{lc_agent_name:t.name}})),this.#o=t.version??this.#o,!t.model)throw new Error("`model` option is required to create an agent.");typeof t.model!="string"&&Ie(t.model);let o=this.options.middleware?.filter(m=>m.tools).flatMap(m=>m.tools)??[],r=[...t.tools??[],...o],s=new Set(r.filter(re).filter(m=>"returnDirect"in m&&m.returnDirect).map(m=>m.name)),i=!!this.options.middleware?.some(m=>m.wrapModelCall),{state:l,input:u,output:c}=It(this.options.responseFormat!==void 0||i,this.options.stateSchema,this.options.middleware),d=new _t(l,{input:u,output:c,context:this.options.contextSchema}),g=[],p=[],h=[],I=[],V=[];this.#s=new Wt({model:this.options.model,systemMessage:Nt(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:r,shouldReturnDirect:s,signal:this.options.signal,wrapModelCallHookMiddleware:V});let k=new Set,T=this.options.middleware??[];for(let m=0;m<T.length;m++){let y,v,_,C,f=T[m];if(k.has(f.name))throw new Error(`Middleware ${f.name} is defined multiple times`);if(k.add(f.name),f.beforeAgent){y=new Gt(f,{getState:()=>this.#t.getState(f.name)}),this.#t.addNode(f,y);let b=`${f.name}.before_agent`;g.push({index:m,name:b,allowed:Y(f.beforeAgent)}),d.addNode(b,y,y.nodeOptions)}if(f.beforeModel){v=new Vt(f,{getState:()=>this.#t.getState(f.name)}),this.#t.addNode(f,v);let b=`${f.name}.before_model`;p.push({index:m,name:b,allowed:Y(f.beforeModel)}),d.addNode(b,v,v.nodeOptions)}if(f.afterModel){_=new Zt(f,{getState:()=>this.#t.getState(f.name)}),this.#t.addNode(f,_);let b=`${f.name}.after_model`;h.push({index:m,name:b,allowed:Y(f.afterModel)}),d.addNode(b,_,_.nodeOptions)}if(f.afterAgent){C=new Yt(f,{getState:()=>this.#t.getState(f.name)}),this.#t.addNode(f,C);let b=`${f.name}.after_agent`;I.push({index:m,name:b,allowed:Y(f.afterAgent)}),d.addNode(b,C,C.nodeOptions)}f.wrapModelCall&&V.push([f,()=>this.#t.getState(f.name)])}d.addNode(O,this.#s);let L=T.some(m=>m.wrapToolCall),R=r.filter(re);if(R.length>0||L){let m=new Jt(R,{signal:this.options.signal,wrapToolCall:Pt(T)});d.addNode(P,m)}let D;g.length>0?D=g[0].name:p.length>0?D=p[0].name:D=O;let se=p.length>0?p[0].name:O,U=I.length>0?I[I.length-1].name:S;d.addEdge(rt,D);let E=R.length>0||L;for(let m=0;m<g.length;m++){let y=g[m],v=y.name,_=m===g.length-1?se:g[m+1].name;if(y.allowed&&y.allowed.length>0){let C=y.allowed.map(b=>G(b)).filter(b=>b!=="tools"||E),f=Array.from(new Set([_,...C.map(b=>b===S?U:b)]));d.addConditionalEdges(v,this.#d(R,_,U,E),f)}else d.addEdge(v,_)}for(let m=0;m<p.length;m++){let y=p[m],v=y.name,_=m===p.length-1?O:p[m+1].name;if(y.allowed&&y.allowed.length>0){let C=y.allowed.map(b=>G(b)).filter(b=>b!=="tools"||E),f=Array.from(new Set([_,...C]));d.addConditionalEdges(v,this.#m(R,_,E),f)}else d.addEdge(v,_)}let x=h.at(-1);if(h.length>0&&x)d.addEdge(O,x.name);else{let m=this.#a(R,!1,E).map(y=>y===S?U:y);m.length===1?d.addEdge(O,m[0]):d.addConditionalEdges(O,this.#c(U),m)}for(let m=h.length-1;m>0;m--){let y=h[m],v=y.name,_=h[m-1].name;if(y.allowed&&y.allowed.length>0){let C=y.allowed.map(b=>G(b)).filter(b=>b!=="tools"||E),f=Array.from(new Set([_,...C]));d.addConditionalEdges(v,this.#r(R,y.allowed,_,E),f)}else d.addEdge(v,_)}if(h.length>0){let m=h[0],y=m.name,v=this.#a(R,!0,E).filter(f=>f!=="tools"||E),_=!!(m.allowed&&m.allowed.length>0),C=v.map(f=>f===S?U:f);d.addConditionalEdges(y,this.#i(R,_,U,E),C)}for(let m=I.length-1;m>0;m--){let y=I[m],v=y.name,_=I[m-1].name;if(y.allowed&&y.allowed.length>0){let C=y.allowed.map(b=>G(b)).filter(b=>b!=="tools"||E),f=Array.from(new Set([_,...C]));d.addConditionalEdges(v,this.#r(R,y.allowed,_,E),f)}else d.addEdge(v,_)}if(I.length>0){let m=I[0],y=m.name;if(m.allowed&&m.allowed.length>0){let v=m.allowed.map(C=>G(C)).filter(C=>C!=="tools"||E),_=Array.from(new Set([S,...v]));d.addConditionalEdges(y,this.#r(R,m.allowed,S,E),_)}else d.addEdge(y,S)}if(E){let m=se;s.size>0?d.addConditionalEdges(P,this.#l(s,U,m),[m,U]):d.addEdge(P,m)}this.#e=d.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#e}get checkpointer(){return this.#e.checkpointer}set checkpointer(t){this.#e.checkpointer=t}get store(){return this.#e.store}set store(t){this.#e.store=t}withConfig(t){return new Xt(this.options,H(this.#n,t))}#a(t,n=!1,o=t.length>0){let r=[];return o&&r.push(P),n&&r.push(O),r.push(S),r}#l(t,n,o){return r=>{let s=r.messages,i=s[s.length-1];return M.isInstance(i)&&i.name&&t.has(i.name)?this.options.responseFormat?o:n:o}}#c(t=S){return n=>{let o=n.messages.at(-1);if(!w.isInstance(o)||!o.tool_calls||o.tool_calls.length===0||o.tool_calls.every(s=>s.name.startsWith("extract-")))return t;if(this.#o==="v1")return P;let r=o.tool_calls.filter(s=>!s.name.startsWith("extract-"));return r.length===0?t:r.map(s=>new $(P,{...n,lg_tool_call:s}))}}#i(t,n,o,r=t.length>0){let s=!!this.options.responseFormat;return i=>{let l=i,u=l.messages,c=u.at(-1);if(w.isInstance(c)&&(!c.tool_calls||c.tool_calls.length===0))return o;if(n&&l.jumpTo){let T=G(l.jumpTo);return T===S?o:T==="tools"?r?new $(P,{...i,jumpTo:void 0}):o:new $(O,{...i,jumpTo:void 0})}let d=u.filter(M.isInstance),g=u.filter(w.isInstance).at(-1),p=g?.tool_calls?.filter(T=>!d.some(L=>L.tool_call_id===T.id));if(p&&p.length>0)return this.#o==="v1"?P:p.map(T=>new $(P,{...i,lg_tool_call:T}));let h=g?.tool_calls?.some(T=>T.name.startsWith("extract-"));if(p&&p.length===0&&!h&&s)return O;if(!w.isInstance(c)||!c.tool_calls||c.tool_calls.length===0)return o;let I=c.tool_calls.every(T=>T.name.startsWith("extract-")),V=c.tool_calls.some(T=>!T.name.startsWith("extract-"));if(I||!V)return o;if(this.#o==="v1")return P;let k=c.tool_calls.filter(T=>!T.name.startsWith("extract-"));return k.length===0?o:k.map(T=>new $(P,{...i,lg_tool_call:T}))}}#r(t,n,o,r=t.length>0){let s=new Set(n.map(i=>G(i)));return i=>{let l=i;if(l.jumpTo){let u=G(l.jumpTo);if(u===S&&s.has(S))return S;if(u==="tools"&&s.has("tools"))return r?new $(P,{...i,jumpTo:void 0}):S;if(u==="model_request"&&s.has("model_request"))return new $(O,{...i,jumpTo:void 0})}return o}}#d(t,n,o,r=t.length>0){return s=>{let i=s;if(!i.jumpTo)return n;let l=G(i.jumpTo);return l===S?o:l==="tools"?r?new $(P,{...s,jumpTo:void 0}):o:new $(O,{...s,jumpTo:void 0})}}#m(t,n,o=t.length>0){return r=>{let s=r;if(!s.jumpTo)return n;let i=G(s.jumpTo);return i===S?S:i==="tools"?o?new $(P,{...r,jumpTo:void 0}):S:new $(O,{...r,jumpTo:void 0})}}async#u(t,n){if(!this.options.middleware||this.options.middleware.length===0||t instanceof j||!t)return t;let o=await Lt(this.options.middleware,t),r={...(await this.#e.getState(n).catch(()=>({values:{}}))).values,...t};if(!r)return r;for(let[s,i]of Object.entries(o))s in r||(r[s]=i);return r}async invoke(t,n){let o=H(this.#n,n),r=await this.#u(t,o);return this.#e.invoke(r,o)}async stream(t,n){let o=H(this.#n,n),r=await this.#u(t,o);return this.#e.stream(r,o)}async drawMermaidPng(t){let n=await(await(await this.#e.getGraphAsync()).drawMermaidPng(t)).arrayBuffer();return new Uint8Array(n)}async drawMermaid(t){return(await this.#e.getGraphAsync()).drawMermaid(t)}streamEvents(t,n,o){let r=H(this.#n,n);return this.#e.streamEvents(t,{...r,version:n?.version??"v2"},o)}getGraphAsync(t){return this.#e.getGraphAsync(t)}getState(t,n){return this.#e.getState(t,n)}getStateHistory(t,n){return this.#e.getStateHistory(t,n)}getSubgraphs(t,n){return this.#e.getSubgraphs(t,n)}getSubgraphsAsync(t,n){return this.#e.getSubgraphsAsync(t,n)}updateState(t,n,o){return this.#e.updateState(t,n,o)}get builder(){return this.#e.builder}};function xo(e){return new qt(e)}var Co=a.function().args(a.custom(),a.custom(),a.custom()).returns(a.union([a.string(),a.promise(a.string())])),So=["approve","edit","reject"],ko=a.enum(So),Eo=a.object({allowedDecisions:a.array(ko),description:a.union([a.string(),Co]).optional(),argsSchema:a.record(a.any()).optional()}),zs=a.object({interruptOn:a.record(a.union([a.boolean(),Eo])).optional(),descriptionPrefix:a.string().default("Tool execution requires approval")});var je=`<role>
|
|
29
|
+
Context Extraction Assistant
|
|
30
|
+
</role>
|
|
31
|
+
|
|
32
|
+
<primary_objective>
|
|
33
|
+
Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
|
|
34
|
+
</primary_objective>
|
|
35
|
+
|
|
36
|
+
<objective_information>
|
|
37
|
+
You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
|
|
38
|
+
This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
|
|
39
|
+
</objective_information>
|
|
40
|
+
|
|
41
|
+
<instructions>
|
|
42
|
+
The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
|
|
43
|
+
You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
|
|
44
|
+
</instructions>
|
|
45
|
+
|
|
46
|
+
The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
|
|
47
|
+
|
|
48
|
+
With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
|
|
49
|
+
Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
|
|
50
|
+
|
|
51
|
+
<messages>
|
|
52
|
+
Messages to summarize:
|
|
53
|
+
{messages}
|
|
54
|
+
</messages>`,Io="Here is a summary of the conversation to date:",Pe=20,Ao=4e3,Ro=15,Qt=5,Oo=a.function().args(a.array(a.custom())).returns(a.union([a.number(),a.promise(a.number())])),ge=a.object({fraction:a.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:a.number().positive("Tokens must be greater than 0").optional(),messages:a.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length>=1,{message:"At least one of fraction, tokens, or messages must be provided"}),ot=a.object({fraction:a.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:a.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:a.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine(e=>[e.fraction,e.tokens,e.messages].filter(t=>t!==void 0).length===1,{message:"Exactly one of fraction, tokens, or messages must be provided"}),eo=a.object({model:a.custom(),trigger:a.union([ge,a.array(ge)]).optional(),keep:ot.optional(),tokenCounter:Oo.optional(),summaryPrompt:a.string().default(je),trimTokensToSummarize:a.number().optional(),summaryPrefix:a.string().optional(),maxTokensBeforeSummary:a.number().optional(),messagesToKeep:a.number().optional()});function Le(e){if("profile"in e&&typeof e.profile=="object"&&e.profile&&"maxInputTokens"in e.profile&&(typeof e.profile.maxInputTokens=="number"||e.profile.maxInputTokens==null))return e.profile.maxInputTokens??void 0;if("model"in e&&typeof e.model=="string")return Ge(e.model);if("modelName"in e&&typeof e.modelName=="string")return Ge(e.modelName)}function No(e){let{data:t,error:n}=pt(eo,e);if(n)throw new Error(`Invalid summarization middleware options: ${z.prettifyError(n)}`);return A({name:"SummarizationMiddleware",contextSchema:eo.extend({model:a.custom().optional()}),beforeModel:async(o,r)=>{let s=t.trigger,i=t.keep;t.maxTokensBeforeSummary!==void 0&&(console.warn("maxTokensBeforeSummary is deprecated. Use `trigger: { tokens: value }` instead."),s===void 0&&(s={tokens:t.maxTokensBeforeSummary})),t.messagesToKeep!==void 0&&(console.warn("messagesToKeep is deprecated. Use `keep: { messages: value }` instead."),(!i||i&&"messages"in i&&i.messages===Pe)&&(i={messages:t.messagesToKeep}));let l=r.context?.trigger!==void 0?r.context.trigger:s,u=r.context?.keep!==void 0?r.context.keep:i??{messages:Pe},c=ot.parse(u),d=[];l===void 0?d=[]:Array.isArray(l)?d=l.map(x=>ge.parse(x)):d=[ge.parse(l)];let g=d.some(x=>"fraction"in x)||"fraction"in c,p=typeof t.model=="string"?await X(t.model):t.model;if(g&&!Le(p))throw new Error("Model profile information is required to use fractional token limits. Use absolute token counts instead.");let h=r.context?.summaryPrompt===je?t.summaryPrompt??je:r.context?.summaryPrompt??t.summaryPrompt??je,I=r.context.summaryPrefix??t.summaryPrefix??Io,V=r.context?.trimTokensToSummarize!==void 0?r.context.trimTokensToSummarize:t.trimTokensToSummarize??Ao;jo(o.messages);let k=r.context?.tokenCounter!==void 0?r.context.tokenCounter:t.tokenCounter??Ne,T=await k(o.messages);if(!await Do(o.messages,T,d,p))return;let{systemPrompt:L,conversationMessages:R}=Po(o.messages),D=await $o(R,c,k,p);if(D<=0)return;let{messagesToSummarize:se,preservedMessages:U}=Lo(L,R,D),E=new K({content:`${I}
|
|
55
|
+
|
|
56
|
+
${await zo(se,p,h,k,V,r)}`,id:ze(),additional_kwargs:{lc_source:"summarization"}});return{messages:[new Be({id:bt}),E,...U]}}})}function jo(e){for(let t of e)t.id||(t.id=ze())}function Po(e){return e.length>0&&B.isInstance(e[0])?{systemPrompt:e[0],conversationMessages:e.slice(1)}:{conversationMessages:e}}function Lo(e,t,n){let o=t.slice(0,n),r=t.slice(n);return e&&o.unshift(e),{messagesToSummarize:o,preservedMessages:r}}async function Do(e,t,n,o){if(n.length===0)return!1;for(let r of n){let s=!0,i=!1;if(r.messages!==void 0&&(i=!0,e.length<r.messages&&(s=!1)),r.tokens!==void 0&&(i=!0,t<r.tokens&&(s=!1)),r.fraction!==void 0){i=!0;let l=Le(o);typeof l=="number"?t<Math.floor(l*r.fraction)&&(s=!1):s=!1}if(i&&s)return!0}return!1}async function $o(e,t,n,o){if("tokens"in t||"fraction"in t){let r=await Uo(e,t,n,o);return typeof r=="number"?r:to(e,Pe)}return to(e,t.messages??Pe)}async function Uo(e,t,n,o){if(e.length===0)return 0;let r;if("fraction"in t&&t.fraction!==void 0){let d=Le(o);if(typeof d!="number")return;r=Math.floor(d*t.fraction)}else if("tokens"in t&&t.tokens!==void 0)r=Math.floor(t.tokens);else return;if(r<=0&&(r=1),await n(e)<=r)return 0;let s=0,i=e.length,l=e.length,u=Math.floor(Math.log2(e.length))+1;for(let d=0;d<u&&!(s>=i);d++){let g=Math.floor((s+i)/2);await n(e.slice(g))<=r?(l=g,i=g):s=g+1}if(l===e.length&&(l=s),l>=e.length){if(e.length===1)return 0;l=e.length-1}let c=ro(e,l);if(c<=l)return c;for(let d=l;d>=0;d--)if(oo(e,d))return d;return 0}function to(e,t){if(e.length<=t)return 0;let n=e.length-t,o=ro(e,n);if(o<=n)return o;for(let r=n;r>=0;r--)if(oo(e,r))return r;return 0}function oo(e,t){if(t>=e.length)return!0;if(t<e.length&&w.isInstance(e[t])&&le(e[t]))return!1;let n=Math.max(0,t-Qt),o=Math.min(e.length,t+Qt);for(let r=n;r<o;r++){if(!le(e[r]))continue;let s=no(e[r]);if(Bo(e,r,t,s))return!1}return!0}function no(e){let t=new Set;if(e.tool_calls)for(let n of e.tool_calls){let o=typeof n=="object"&&"id"in n?n.id:null;o&&t.add(o)}return t}function ro(e,t){if(t>=e.length||!M.isInstance(e[t]))return t;let n=new Set,o=t;for(;o<e.length&&M.isInstance(e[o]);){let r=e[o];r.tool_call_id&&n.add(r.tool_call_id),o++}for(let r=t-1;r>=0;r--){let s=e[r];if(w.isInstance(s)&&le(s)){let i=no(s);for(let l of n)if(i.has(l))return r}}return o}function Bo(e,t,n,o){for(let r=t+1;r<e.length;r++){let s=e[r];if(M.isInstance(s)&&o.has(s.tool_call_id)&&t<n!=r<n)return!0}return!1}async function zo(e,t,n,o,r,s){if(!e.length)return"No previous conversation history.";let i=await Wo(e,o,r);if(!i.length)return"Previous conversation was too long to summarize.";let l=lt(i);try{let u=n.replace("{messages}",l),c=H(ct(s)??{},{metadata:{lc_source:"summarization"}}),d=(await t.invoke(u,c)).content;return typeof d=="string"?d.trim():Array.isArray(d)?d.map(g=>typeof g=="string"?g:typeof g=="object"&&g!==null&&"text"in g?g.text:"").join("").trim():"Error generating summary: Invalid response format"}catch(u){return`Error generating summary: ${u}`}}async function Wo(e,t,n){if(n===void 0)return e;try{return await Je(e,{maxTokens:n,tokenCounter:async o=>t(o),strategy:"last",allowPartial:!0,includeSystem:!0})}catch{return e.slice(-Ro)}}var da=a.object({model:a.string().or(a.instanceof(yt)).optional(),systemPrompt:a.string().optional(),maxTools:a.number().optional(),alwaysInclude:a.array(a.string()).optional()});var wa=a.object({applyToInput:a.boolean().optional(),applyToOutput:a.boolean().optional(),applyToToolResults:a.boolean().optional()});var _a=a.object({rules:a.record(a.string(),a.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var Fo=["continue","error","end"],Ho="continue";var Jo=a.enum(Fo).default(Ho);a.object({toolName:a.string().optional(),threadLimit:a.number().optional(),runLimit:a.number().optional(),exitBehavior:Jo});var Oa=a.object({threadToolCallCount:a.record(a.string(),a.number()).default({}),runToolCallCount:a.record(a.string(),a.number()).default({})});var Go=a.enum(["pending","in_progress","completed"]).describe("Status of the todo"),Vo=a.object({content:a.string().describe("Content of the todo item"),status:Go}),Ba=a.object({todos:a.array(Vo).default([])});var Zo="end",Yo=a.object({threadLimit:a.number().optional(),runLimit:a.number().optional(),exitBehavior:a.enum(["error","end"]).optional()}),Ko=a.object({threadModelCallCount:a.number().default(0),runModelCallCount:a.number().default(0)}),so=class extends Error{constructor({threadLimit:e,runLimit:t,threadCount:n,runCount:o}){let r=[];typeof e=="number"&&typeof n=="number"&&r.push(`thread level call limit reached with ${n} model calls`),typeof t=="number"&&typeof o=="number"&&r.push(`run level call limit reached with ${o} model calls`),super(`Model call limits exceeded${r.length>0?`: ${r.join(", ")}`:""}`),this.name="ModelCallLimitMiddlewareError"}};function qo(e){return A({name:"ModelCallLimitMiddleware",contextSchema:Yo,stateSchema:Ko,beforeModel:{canJumpTo:["end"],hook:(t,n)=>{let o=n.context.exitBehavior??e?.exitBehavior??Zo;o==="throw"&&(console.warn("The 'throw' exit behavior is deprecated. Please use 'error' instead."),o="error");let r=n.context.threadLimit??e?.threadLimit,s=n.context.runLimit??e?.runLimit,i=t.threadModelCallCount,l=t.runModelCallCount;if(typeof r=="number"&&r<=i){let u=new so({threadLimit:r,threadCount:i});if(o==="end")return{jumpTo:"end",messages:[new w(u.message)]};throw u}if(typeof s=="number"&&s<=l){let u=new so({runLimit:s,runCount:l});if(o==="end")return{jumpTo:"end",messages:[new w(u.message)]};throw u}return t}},afterModel:t=>({runModelCallCount:t.runModelCallCount+1,threadModelCallCount:t.threadModelCallCount+1}),afterAgent:()=>({runModelCallCount:0})})}var De=a.object({maxRetries:a.number().min(0).default(2),retryOn:a.union([a.function().args(a.instanceof(Error)).returns(a.boolean()),a.array(a.custom())]).default(()=>()=>!0),backoffFactor:a.number().min(0).default(2),initialDelayMs:a.number().min(0).default(1e3),maxDelayMs:a.number().min(0).default(6e4),jitter:a.boolean().default(!0)});var si=a.object({onFailure:a.union([a.literal("error"),a.literal("continue"),a.function().args(a.instanceof(Error)).returns(a.string())]).default("continue")}).merge(De);var fi=a.object({tools:a.array(a.union([a.custom(),a.custom(),a.string()])).optional(),onFailure:a.union([a.literal("error"),a.literal("continue"),a.literal("raise"),a.literal("return_message"),a.function().args(a.instanceof(Error)).returns(a.string())]).default("continue")}).merge(De);var Ci=a.object({enableCaching:a.boolean().optional(),ttl:a.enum(["5m","1h"]).optional(),minMessagesToCache:a.number().optional(),unsupportedModelBehavior:a.enum(["ignore","warn","raise"]).optional()});export{A as a,xo as b,No as c,qo as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
import e from"./PKHQW7QU.js";import d from"./HOCTVCHH.js";import c from"./AFLQZIKS.js";import b from"./EBRNMPPO.js";import{a,c as s}from"./W2JAKE2M.js";import"./5W7S2RS4.js";import"./NXKKG5TK.js";import{v as i,z as r}from"./MAV3DW27.js";import"./ADYIXCSG.js";import"./4RZPOYZ7.js";import"./6LZ6GOHF.js";import"./CJIV4KJZ.js";import"./IKEF7ZHH.js";import"./WNS5ZUF5.js";import"./ZEYIBYSF.js";import"./YIMNOUTF.js";export default $arcgis.t(([,,,,,,,,,,,o])=>{var t=class extends i{constructor(){super(...arguments),this.agent=o}static{this.properties={referenceElement:1}}#t;#i;getContext(){if(!this.#t)throw new Error("arcgis-assistant-data-exploration-agent requires a mapView");return{mapView:this.#t}}load(){this.#t=a(this,"arcgis-assistant-data-exploration-agent"),this.#i=s(this)}disconnectedCallback(){this.#i?.unregister(this.agent.id),super.disconnectedCallback()}};r("arcgis-assistant-data-exploration-agent",t);return t},"identity/IdentityManager","portal/Portal","config","core/reactiveUtils","layers/FeatureLayer","request","views/LinkChartView","rest/knowledgeGraphService",b,c,d,e)
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
|
|
2
|
+
var s=t=>t.replace(o,(e,n)=>`${n===0?"":"-"}${e.toLowerCase()}`),o=/[A-Z]+(?![a-z])|[A-Z]/gu;var r="randomUUID"in crypto,c=()=>{if(r)return crypto.randomUUID();let t=crypto.getRandomValues(new Uint16Array(8));t[3]=t[3]&4095|16384,t[4]=t[4]&16383|32768;let e=n=>t[n].toString(16).padStart(4,"0");return`${e(0)+e(1)}-${e(2)}-${e(3)}-${e(4)}-${e(5)}${e(6)}${e(7)}`};export{s as a,c as b};
|