agent-scene-toolkit 0.1.4 → 0.1.6

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/index.d.cts CHANGED
@@ -152,6 +152,8 @@ interface AgentOptions {
152
152
  /** API Key,优先级高于环境变量 OPENAI_API_KEY */
153
153
  apiKey?: string;
154
154
  };
155
+ /** LangGraph 递归调用限制(单 Agent 默认 25,多 Agent 默认 50) */
156
+ recursionLimit?: number;
155
157
  }
156
158
  /**
157
159
  * `agent.chat()` 调用参数。
@@ -447,7 +449,7 @@ declare function buildPromptChain(params: {
447
449
  * @throws 当 LLM 初始化失败或 stream() 执行失败时抛出异常
448
450
  */
449
451
  declare function buildSingleGraph(params: {
450
- /** 完整的 system prompt(4 层拼接后) */
452
+ /** 完整的 system prompt(3 层拼接后) */
451
453
  systemPrompt: string;
452
454
  /** 当前场景激活的工具列表 */
453
455
  tools: StructuredToolInterface[];
@@ -465,7 +467,15 @@ declare function buildSingleGraph(params: {
465
467
  callbacks: BaseCallbackHandler[];
466
468
  /** 底层 LLM 网关配置(OpenAI 兼容) */
467
469
  llm?: AgentOptions['llm'];
468
- }): Promise<_langchain_core_utils_stream.IterableReadableStream<["updates", Record<string, any>] | ["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]]>>;
470
+ /** 递归调用限制(默认 25) */
471
+ recursionLimit?: number;
472
+ /** 运行时场景(可选),有值时启用动态 scene prompt 刷新 */
473
+ scene?: Scene;
474
+ /** 传给 scene.prompt(ctx) 的动态数据(可选) */
475
+ sceneContext?: Record<string, any>;
476
+ /** Profile + ToolKit prompt 的静态拼接(不含 scene prompt),用于 middleware 重新拼接 */
477
+ staticPromptParts?: string;
478
+ }): Promise<_langchain_core_utils_stream.IterableReadableStream<["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]] | ["updates", Record<string, any>]>>;
469
479
 
470
480
  /**
471
481
  * 构建多 Agent Supervisor 图并返回双模式流。
@@ -491,7 +501,7 @@ declare function buildSingleGraph(params: {
491
501
  * @throws 当 LLM 初始化失败、Worker 全部创建失败或 stream() 执行失败时抛出异常
492
502
  */
493
503
  declare function buildSupervisorGraph(params: {
494
- /** Supervisor 的 Prompt(4 层拼接后,用于 Supervisor Agent) */
504
+ /** Supervisor 的 Prompt(3 层拼接后,用于 Supervisor Agent) */
495
505
  supervisorPrompt: string;
496
506
  /** 所有 AgentProfile 列表 */
497
507
  agents: AgentProfile[];
@@ -499,7 +509,7 @@ declare function buildSupervisorGraph(params: {
499
509
  supervisorName: string;
500
510
  /** 当前场景激活的工具列表(所有 Worker 共享) */
501
511
  tools: StructuredToolInterface[];
502
- /** 各 Worker 的 Prompt 映射(profile.name → 4 层拼接后的 prompt) */
512
+ /** 各 Worker 的 Prompt 映射(profile.name → 3 层拼接后的 prompt) */
503
513
  workerPrompts: Map<string, string>;
504
514
  /** 用户消息 */
505
515
  message: string;
@@ -513,7 +523,15 @@ declare function buildSupervisorGraph(params: {
513
523
  callbacks: BaseCallbackHandler[];
514
524
  /** 底层 LLM 网关配置(OpenAI 兼容) */
515
525
  llm?: AgentOptions['llm'];
516
- }): Promise<_langchain_core_utils_stream.IterableReadableStream<["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]] | ["updates", Record<string, _langchain_langgraph.UpdateType<_langchain_langgraph.StateDefinition> | _langchain_langgraph.UpdateType<any>>]>>;
526
+ /** 递归调用限制(默认 50) */
527
+ recursionLimit?: number;
528
+ /** 运行时场景(可选),有值时启用动态 scene prompt 刷新 */
529
+ scene?: Scene;
530
+ /** 传给 scene.prompt(ctx) 的动态数据(可选) */
531
+ sceneContext?: Record<string, any>;
532
+ /** 各角色的静态 prompt 部分映射(profile.name → Profile + ToolKit prompt 的拼接,不含 scene prompt) */
533
+ staticPromptPartsMap?: Map<string, string>;
534
+ }): Promise<_langchain_core_utils_stream.IterableReadableStream<["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]] | ["updates", Record<string, _langchain_langgraph.UpdateType<any> | _langchain_langgraph.UpdateType<_langchain_langgraph.StateDefinition>>]>>;
517
535
 
518
536
  /**
519
537
  * 将 LangGraph `stream()` 的双模式流(messages + updates)
package/dist/index.d.ts CHANGED
@@ -152,6 +152,8 @@ interface AgentOptions {
152
152
  /** API Key,优先级高于环境变量 OPENAI_API_KEY */
153
153
  apiKey?: string;
154
154
  };
155
+ /** LangGraph 递归调用限制(单 Agent 默认 25,多 Agent 默认 50) */
156
+ recursionLimit?: number;
155
157
  }
156
158
  /**
157
159
  * `agent.chat()` 调用参数。
@@ -447,7 +449,7 @@ declare function buildPromptChain(params: {
447
449
  * @throws 当 LLM 初始化失败或 stream() 执行失败时抛出异常
448
450
  */
449
451
  declare function buildSingleGraph(params: {
450
- /** 完整的 system prompt(4 层拼接后) */
452
+ /** 完整的 system prompt(3 层拼接后) */
451
453
  systemPrompt: string;
452
454
  /** 当前场景激活的工具列表 */
453
455
  tools: StructuredToolInterface[];
@@ -465,7 +467,15 @@ declare function buildSingleGraph(params: {
465
467
  callbacks: BaseCallbackHandler[];
466
468
  /** 底层 LLM 网关配置(OpenAI 兼容) */
467
469
  llm?: AgentOptions['llm'];
468
- }): Promise<_langchain_core_utils_stream.IterableReadableStream<["updates", Record<string, any>] | ["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]]>>;
470
+ /** 递归调用限制(默认 25) */
471
+ recursionLimit?: number;
472
+ /** 运行时场景(可选),有值时启用动态 scene prompt 刷新 */
473
+ scene?: Scene;
474
+ /** 传给 scene.prompt(ctx) 的动态数据(可选) */
475
+ sceneContext?: Record<string, any>;
476
+ /** Profile + ToolKit prompt 的静态拼接(不含 scene prompt),用于 middleware 重新拼接 */
477
+ staticPromptParts?: string;
478
+ }): Promise<_langchain_core_utils_stream.IterableReadableStream<["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]] | ["updates", Record<string, any>]>>;
469
479
 
470
480
  /**
471
481
  * 构建多 Agent Supervisor 图并返回双模式流。
@@ -491,7 +501,7 @@ declare function buildSingleGraph(params: {
491
501
  * @throws 当 LLM 初始化失败、Worker 全部创建失败或 stream() 执行失败时抛出异常
492
502
  */
493
503
  declare function buildSupervisorGraph(params: {
494
- /** Supervisor 的 Prompt(4 层拼接后,用于 Supervisor Agent) */
504
+ /** Supervisor 的 Prompt(3 层拼接后,用于 Supervisor Agent) */
495
505
  supervisorPrompt: string;
496
506
  /** 所有 AgentProfile 列表 */
497
507
  agents: AgentProfile[];
@@ -499,7 +509,7 @@ declare function buildSupervisorGraph(params: {
499
509
  supervisorName: string;
500
510
  /** 当前场景激活的工具列表(所有 Worker 共享) */
501
511
  tools: StructuredToolInterface[];
502
- /** 各 Worker 的 Prompt 映射(profile.name → 4 层拼接后的 prompt) */
512
+ /** 各 Worker 的 Prompt 映射(profile.name → 3 层拼接后的 prompt) */
503
513
  workerPrompts: Map<string, string>;
504
514
  /** 用户消息 */
505
515
  message: string;
@@ -513,7 +523,15 @@ declare function buildSupervisorGraph(params: {
513
523
  callbacks: BaseCallbackHandler[];
514
524
  /** 底层 LLM 网关配置(OpenAI 兼容) */
515
525
  llm?: AgentOptions['llm'];
516
- }): Promise<_langchain_core_utils_stream.IterableReadableStream<["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]] | ["updates", Record<string, _langchain_langgraph.UpdateType<_langchain_langgraph.StateDefinition> | _langchain_langgraph.UpdateType<any>>]>>;
526
+ /** 递归调用限制(默认 50) */
527
+ recursionLimit?: number;
528
+ /** 运行时场景(可选),有值时启用动态 scene prompt 刷新 */
529
+ scene?: Scene;
530
+ /** 传给 scene.prompt(ctx) 的动态数据(可选) */
531
+ sceneContext?: Record<string, any>;
532
+ /** 各角色的静态 prompt 部分映射(profile.name → Profile + ToolKit prompt 的拼接,不含 scene prompt) */
533
+ staticPromptPartsMap?: Map<string, string>;
534
+ }): Promise<_langchain_core_utils_stream.IterableReadableStream<["messages", [langchain.BaseMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>, _langchain_core_messages.MessageType>, Record<string, any>]] | ["updates", Record<string, _langchain_langgraph.UpdateType<any> | _langchain_langgraph.UpdateType<_langchain_langgraph.StateDefinition>>]>>;
517
535
 
518
536
  /**
519
537
  * 将 LangGraph `stream()` 的双模式流(messages + updates)
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { MemorySaver } from '@langchain/langgraph';
2
2
  import { ChatOpenAI } from '@langchain/openai';
3
- import { createAgent, createMiddleware } from 'langchain';
4
- import { HumanMessage, AIMessageChunk, ToolMessage } from '@langchain/core/messages';
3
+ import { createMiddleware, createAgent } from 'langchain';
4
+ import { HumanMessage, SystemMessage, AIMessageChunk, ToolMessage } from '@langchain/core/messages';
5
5
  import { createReactAgent } from '@langchain/langgraph/prebuilt';
6
6
  import { createSupervisor } from '@langchain/langgraph-supervisor';
7
7
  import { DynamicTool } from '@langchain/core/tools';
@@ -48,6 +48,33 @@ function defineKnowledgeBase(input) {
48
48
  }
49
49
 
50
50
  // src/prompt.ts
51
+ function removeCircularReferences(obj) {
52
+ const seen = /* @__PURE__ */ new WeakSet();
53
+ function clone(value) {
54
+ if (value === null || typeof value !== "object") {
55
+ return value;
56
+ }
57
+ if (seen.has(value)) {
58
+ return "[Circular Reference]";
59
+ }
60
+ seen.add(value);
61
+ if (Array.isArray(value)) {
62
+ return value.map((item) => clone(item));
63
+ }
64
+ const cloned = {};
65
+ for (const key in value) {
66
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
67
+ try {
68
+ cloned[key] = clone(value[key]);
69
+ } catch (error) {
70
+ cloned[key] = "[Unserializable]";
71
+ }
72
+ }
73
+ }
74
+ return cloned;
75
+ }
76
+ return clone(obj);
77
+ }
51
78
  function buildPromptChain(params) {
52
79
  const layers = [
53
80
  // ① Profile — 角色身份提示词
@@ -57,7 +84,8 @@ function buildPromptChain(params) {
57
84
  ];
58
85
  if (params.scene) {
59
86
  try {
60
- const scenePrompt = params.scene.prompt(params.sceneContext ?? {});
87
+ const safeContext = removeCircularReferences(params.sceneContext ?? {});
88
+ const scenePrompt = params.scene.prompt(safeContext);
61
89
  layers.push(scenePrompt);
62
90
  } catch (error) {
63
91
  console.error("[buildPromptChain] Scene.prompt() error:", error);
@@ -88,6 +116,45 @@ async function buildSingleGraph(params) {
88
116
  console.log("[buildSingleGraph] tools:", params.tools.map((t) => t.name));
89
117
  console.log("[buildSingleGraph] threadId:", params.threadId);
90
118
  console.log("[buildSingleGraph] maxMessages:", params.maxMessages);
119
+ const middlewares = [
120
+ // 滑动窗口中间件 — beforeModel 阶段裁剪消息,Checkpointer 仍全量存储
121
+ createMiddleware({
122
+ name: "sliding-window",
123
+ beforeModel: (state) => {
124
+ try {
125
+ const max = params.maxMessages;
126
+ if (!state.messages || state.messages.length <= max) return void 0;
127
+ return { messages: state.messages.slice(-max) };
128
+ } catch (error) {
129
+ console.error("[buildSingleGraph] sliding-window middleware error:", error);
130
+ return void 0;
131
+ }
132
+ }
133
+ })
134
+ ];
135
+ if (params.scene && params.staticPromptParts !== void 0) {
136
+ middlewares.push(
137
+ createMiddleware({
138
+ name: "scene-refresh",
139
+ wrapModelCall: async (request, handler) => {
140
+ try {
141
+ const freshSystemPrompt = buildPromptChain({
142
+ // 使用静态部分 + 最新 scene prompt 重新拼接
143
+ profile: { name: "", systemPrompt: params.staticPromptParts, model: "" },
144
+ toolkitPrompts: [],
145
+ // 已包含在 staticPromptParts 中
146
+ scene: params.scene,
147
+ sceneContext: params.sceneContext
148
+ });
149
+ return handler({ ...request, systemPrompt: freshSystemPrompt });
150
+ } catch (error) {
151
+ console.error("[buildSingleGraph] scene-refresh middleware error:", error);
152
+ return handler(request);
153
+ }
154
+ }
155
+ })
156
+ );
157
+ }
91
158
  let graph;
92
159
  try {
93
160
  graph = createAgent({
@@ -95,22 +162,7 @@ async function buildSingleGraph(params) {
95
162
  tools: params.tools,
96
163
  checkpointer: params.checkpointer,
97
164
  systemPrompt: params.systemPrompt,
98
- // 滑动窗口中间件 — beforeModel 阶段裁剪消息,Checkpointer 仍全量存储
99
- middleware: [
100
- createMiddleware({
101
- name: "sliding-window",
102
- beforeModel: (state) => {
103
- try {
104
- const max = params.maxMessages;
105
- if (!state.messages || state.messages.length <= max) return void 0;
106
- return { messages: state.messages.slice(-max) };
107
- } catch (error) {
108
- console.error("[buildSingleGraph] sliding-window middleware error:", error);
109
- return void 0;
110
- }
111
- }
112
- })
113
- ]
165
+ middleware: middlewares
114
166
  });
115
167
  } catch (error) {
116
168
  const message = error instanceof Error ? error.message : String(error);
@@ -122,7 +174,7 @@ async function buildSingleGraph(params) {
122
174
  { messages: [new HumanMessage(params.message)] },
123
175
  {
124
176
  configurable: { thread_id: params.threadId },
125
- recursionLimit: 25,
177
+ recursionLimit: params.recursionLimit ?? 25,
126
178
  streamMode: ["messages", "updates"],
127
179
  // graph 层透传 callbacks — 追踪完整执行链路(工具调用、节点跳转等)
128
180
  callbacks: callbacksOrUndefined
@@ -148,7 +200,27 @@ async function buildSupervisorGraph(params) {
148
200
  configuration: params.llm?.baseURL ? { baseURL: params.llm.baseURL } : void 0,
149
201
  callbacks: callbacksOrUndefined
150
202
  });
151
- const workerPrompt = params.workerPrompts.get(profile.name) ?? profile.systemPrompt;
203
+ const workerStaticPrompt = params.workerPrompts.get(profile.name) ?? profile.systemPrompt;
204
+ let workerPrompt;
205
+ const workerStaticParts = params.staticPromptPartsMap?.get(profile.name);
206
+ if (params.scene && workerStaticParts !== void 0) {
207
+ workerPrompt = () => {
208
+ try {
209
+ const freshPrompt = buildPromptChain({
210
+ profile: { name: "", systemPrompt: workerStaticParts, model: "" },
211
+ toolkitPrompts: [],
212
+ scene: params.scene,
213
+ sceneContext: params.sceneContext
214
+ });
215
+ return [new SystemMessage(freshPrompt)];
216
+ } catch (error) {
217
+ console.error(`[buildSupervisorGraph] Worker "${profile.name}" scene-refresh error:`, error);
218
+ return [new SystemMessage(workerStaticPrompt)];
219
+ }
220
+ };
221
+ } else {
222
+ workerPrompt = workerStaticPrompt;
223
+ }
152
224
  const worker = createReactAgent({
153
225
  llm: workerLLM,
154
226
  tools: params.tools,
@@ -190,12 +262,32 @@ async function buildSupervisorGraph(params) {
190
262
  console.log("[buildSupervisorGraph] workers:", workers.map((_, i) => workerProfiles[i]?.name));
191
263
  console.log("[buildSupervisorGraph] tools:", params.tools.map((t) => t.name));
192
264
  console.log("[buildSupervisorGraph] threadId:", params.threadId);
265
+ const supervisorStaticParts = params.staticPromptPartsMap?.get(params.supervisorName);
266
+ let supervisorPromptArg;
267
+ if (params.scene && supervisorStaticParts !== void 0) {
268
+ supervisorPromptArg = () => {
269
+ try {
270
+ const freshPrompt = buildPromptChain({
271
+ profile: { name: "", systemPrompt: supervisorStaticParts, model: "" },
272
+ toolkitPrompts: [],
273
+ scene: params.scene,
274
+ sceneContext: params.sceneContext
275
+ });
276
+ return [new SystemMessage(freshPrompt)];
277
+ } catch (error) {
278
+ console.error("[buildSupervisorGraph] Supervisor scene-refresh error:", error);
279
+ return [new SystemMessage(params.supervisorPrompt)];
280
+ }
281
+ };
282
+ } else {
283
+ supervisorPromptArg = params.supervisorPrompt;
284
+ }
193
285
  let workflow;
194
286
  try {
195
287
  workflow = createSupervisor({
196
288
  agents: workers,
197
289
  llm: supervisorLLM,
198
- prompt: params.supervisorPrompt,
290
+ prompt: supervisorPromptArg,
199
291
  // 保留完整消息历史,让前端能追踪 handoff 过程
200
292
  outputMode: "full_history",
201
293
  // 滑动窗口 — 只裁剪发给 LLM 的消息,Checkpointer 仍全量存储
@@ -233,7 +325,7 @@ async function buildSupervisorGraph(params) {
233
325
  { messages: [new HumanMessage(params.message)] },
234
326
  {
235
327
  configurable: { thread_id: params.threadId },
236
- recursionLimit: 50,
328
+ recursionLimit: params.recursionLimit ?? 50,
237
329
  // 多 Agent 需要更高的递归限制
238
330
  streamMode: ["messages", "updates"],
239
331
  callbacks: callbacksOrUndefined
@@ -570,6 +662,16 @@ var Agent = class {
570
662
  );
571
663
  }
572
664
  }
665
+ let staticPromptPartsMap;
666
+ if (scene) {
667
+ staticPromptPartsMap = /* @__PURE__ */ new Map();
668
+ for (const profile of this.options.agents) {
669
+ staticPromptPartsMap.set(
670
+ profile.name,
671
+ [profile.systemPrompt, ...toolkitPrompts].filter(Boolean).join("\n\n")
672
+ );
673
+ }
674
+ }
573
675
  stream = await buildSupervisorGraph({
574
676
  supervisorPrompt,
575
677
  agents: this.options.agents,
@@ -581,10 +683,16 @@ var Agent = class {
581
683
  checkpointer: this.options.checkpointer,
582
684
  maxMessages: this.options.maxMessages,
583
685
  callbacks: this.options.callbacks,
584
- llm: this.options.llm
686
+ llm: this.options.llm,
687
+ recursionLimit: this.options.recursionLimit,
688
+ // Scene 动态刷新所需参数
689
+ scene,
690
+ sceneContext: chatOptions.sceneContext,
691
+ staticPromptPartsMap
585
692
  });
586
693
  } else {
587
694
  const profile = this.options.agents[0];
695
+ const staticPromptParts = [profile.systemPrompt, ...toolkitPrompts].filter(Boolean).join("\n\n");
588
696
  const systemPrompt = buildPromptChain({
589
697
  profile,
590
698
  toolkitPrompts,
@@ -600,7 +708,12 @@ var Agent = class {
600
708
  checkpointer: this.options.checkpointer,
601
709
  maxMessages: this.options.maxMessages,
602
710
  callbacks: this.options.callbacks,
603
- llm: this.options.llm
711
+ llm: this.options.llm,
712
+ recursionLimit: this.options.recursionLimit,
713
+ // Scene 动态刷新所需参数 — 有 scene 时 middleware 会在每次 LLM 调用前重新执行 scene.prompt()
714
+ scene,
715
+ sceneContext: chatOptions.sceneContext,
716
+ staticPromptParts: scene ? staticPromptParts : void 0
604
717
  });
605
718
  }
606
719
  yield* transformStream(stream, scene?.onToolEnd);