@illuma-ai/agents 1.1.20 → 1.1.22

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.
Files changed (246) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/llm/bedrock/index.cjs +14 -0
  6. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  7. package/dist/cjs/run.cjs +20 -9
  8. package/dist/cjs/run.cjs.map +1 -1
  9. package/dist/esm/graphs/Graph.mjs +12 -1
  10. package/dist/esm/graphs/Graph.mjs.map +1 -1
  11. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  12. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  13. package/dist/esm/llm/bedrock/index.mjs +14 -0
  14. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  15. package/dist/esm/run.mjs +20 -9
  16. package/dist/esm/run.mjs.map +1 -1
  17. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  18. package/package.json +1 -1
  19. package/src/graphs/Graph.ts +12 -1
  20. package/src/graphs/MultiAgentGraph.ts +105 -1
  21. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  22. package/src/llm/bedrock/index.ts +17 -0
  23. package/src/run.ts +20 -11
  24. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  25. package/src/agents/AgentContext.js +0 -782
  26. package/src/agents/AgentContext.test.js +0 -421
  27. package/src/agents/__tests__/AgentContext.test.js +0 -678
  28. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  29. package/src/common/enum.js +0 -192
  30. package/src/common/index.js +0 -3
  31. package/src/events.js +0 -166
  32. package/src/graphs/Graph.js +0 -1857
  33. package/src/graphs/MultiAgentGraph.js +0 -1092
  34. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  35. package/src/graphs/__tests__/structured-output.test.js +0 -144
  36. package/src/graphs/contextManagement.e2e.test.js +0 -718
  37. package/src/graphs/contextManagement.test.js +0 -485
  38. package/src/graphs/handoffValidation.test.js +0 -276
  39. package/src/graphs/index.js +0 -3
  40. package/src/index.js +0 -28
  41. package/src/instrumentation.js +0 -21
  42. package/src/llm/anthropic/index.js +0 -319
  43. package/src/llm/anthropic/types.js +0 -46
  44. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  45. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  46. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  47. package/src/llm/anthropic/utils/tools.js +0 -25
  48. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  49. package/src/llm/bedrock/index.js +0 -303
  50. package/src/llm/bedrock/types.js +0 -2
  51. package/src/llm/bedrock/utils/index.js +0 -6
  52. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  53. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  54. package/src/llm/fake.js +0 -92
  55. package/src/llm/google/index.js +0 -215
  56. package/src/llm/google/types.js +0 -12
  57. package/src/llm/google/utils/common.js +0 -670
  58. package/src/llm/google/utils/tools.js +0 -111
  59. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  60. package/src/llm/openai/index.js +0 -1033
  61. package/src/llm/openai/types.js +0 -2
  62. package/src/llm/openai/utils/index.js +0 -756
  63. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  64. package/src/llm/openrouter/index.js +0 -261
  65. package/src/llm/openrouter/reasoning.test.js +0 -181
  66. package/src/llm/providers.js +0 -36
  67. package/src/llm/text.js +0 -65
  68. package/src/llm/vertexai/index.js +0 -402
  69. package/src/messages/__tests__/tools.test.js +0 -392
  70. package/src/messages/cache.js +0 -404
  71. package/src/messages/cache.test.js +0 -1167
  72. package/src/messages/content.js +0 -48
  73. package/src/messages/content.test.js +0 -314
  74. package/src/messages/core.js +0 -359
  75. package/src/messages/ensureThinkingBlock.test.js +0 -997
  76. package/src/messages/format.js +0 -973
  77. package/src/messages/formatAgentMessages.test.js +0 -2278
  78. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  79. package/src/messages/formatMessage.test.js +0 -608
  80. package/src/messages/ids.js +0 -18
  81. package/src/messages/index.js +0 -9
  82. package/src/messages/labelContentByAgent.test.js +0 -725
  83. package/src/messages/prune.js +0 -438
  84. package/src/messages/reducer.js +0 -60
  85. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  86. package/src/messages/summarize.js +0 -146
  87. package/src/messages/summarize.test.js +0 -332
  88. package/src/messages/tools.js +0 -90
  89. package/src/mockStream.js +0 -81
  90. package/src/prompts/collab.js +0 -7
  91. package/src/prompts/index.js +0 -3
  92. package/src/prompts/taskmanager.js +0 -58
  93. package/src/run.js +0 -427
  94. package/src/schemas/index.js +0 -3
  95. package/src/schemas/schema-preparation.test.js +0 -370
  96. package/src/schemas/validate.js +0 -314
  97. package/src/schemas/validate.test.js +0 -264
  98. package/src/scripts/abort.js +0 -127
  99. package/src/scripts/ant_web_search.js +0 -130
  100. package/src/scripts/ant_web_search_edge_case.js +0 -133
  101. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  102. package/src/scripts/args.js +0 -41
  103. package/src/scripts/bedrock-cache-debug.js +0 -186
  104. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  105. package/src/scripts/bedrock-merge-test.js +0 -80
  106. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  107. package/src/scripts/caching.js +0 -106
  108. package/src/scripts/cli.js +0 -152
  109. package/src/scripts/cli2.js +0 -119
  110. package/src/scripts/cli3.js +0 -163
  111. package/src/scripts/cli4.js +0 -165
  112. package/src/scripts/cli5.js +0 -165
  113. package/src/scripts/code_exec.js +0 -171
  114. package/src/scripts/code_exec_files.js +0 -180
  115. package/src/scripts/code_exec_multi_session.js +0 -185
  116. package/src/scripts/code_exec_ptc.js +0 -265
  117. package/src/scripts/code_exec_session.js +0 -217
  118. package/src/scripts/code_exec_simple.js +0 -120
  119. package/src/scripts/content.js +0 -111
  120. package/src/scripts/empty_input.js +0 -125
  121. package/src/scripts/handoff-test.js +0 -96
  122. package/src/scripts/image.js +0 -138
  123. package/src/scripts/memory.js +0 -83
  124. package/src/scripts/multi-agent-chain.js +0 -271
  125. package/src/scripts/multi-agent-conditional.js +0 -185
  126. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  127. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  128. package/src/scripts/multi-agent-parallel-start.js +0 -214
  129. package/src/scripts/multi-agent-parallel.js +0 -346
  130. package/src/scripts/multi-agent-sequence.js +0 -184
  131. package/src/scripts/multi-agent-supervisor.js +0 -324
  132. package/src/scripts/multi-agent-test.js +0 -147
  133. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  134. package/src/scripts/parallel-full-metadata-test.js +0 -176
  135. package/src/scripts/parallel-tools-test.js +0 -256
  136. package/src/scripts/programmatic_exec.js +0 -277
  137. package/src/scripts/programmatic_exec_agent.js +0 -168
  138. package/src/scripts/search.js +0 -118
  139. package/src/scripts/sequential-full-metadata-test.js +0 -143
  140. package/src/scripts/simple.js +0 -174
  141. package/src/scripts/single-agent-metadata-test.js +0 -152
  142. package/src/scripts/stream.js +0 -113
  143. package/src/scripts/test-custom-prompt-key.js +0 -132
  144. package/src/scripts/test-handoff-input.js +0 -143
  145. package/src/scripts/test-handoff-preamble.js +0 -227
  146. package/src/scripts/test-handoff-steering.js +0 -353
  147. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  148. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  149. package/src/scripts/test-parallel-handoffs.js +0 -229
  150. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  151. package/src/scripts/test-thinking-handoff.js +0 -132
  152. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  153. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  154. package/src/scripts/test-tools-before-handoff.js +0 -187
  155. package/src/scripts/test_code_api.js +0 -263
  156. package/src/scripts/thinking-bedrock.js +0 -128
  157. package/src/scripts/thinking-vertexai.js +0 -130
  158. package/src/scripts/thinking.js +0 -134
  159. package/src/scripts/tool_search.js +0 -114
  160. package/src/scripts/tools.js +0 -125
  161. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  162. package/src/specs/agent-handoffs.test.js +0 -924
  163. package/src/specs/anthropic.simple.test.js +0 -287
  164. package/src/specs/azure.simple.test.js +0 -381
  165. package/src/specs/cache.simple.test.js +0 -282
  166. package/src/specs/custom-event-await.test.js +0 -148
  167. package/src/specs/deepseek.simple.test.js +0 -189
  168. package/src/specs/emergency-prune.test.js +0 -308
  169. package/src/specs/moonshot.simple.test.js +0 -237
  170. package/src/specs/observability.integration.test.js +0 -1337
  171. package/src/specs/openai.simple.test.js +0 -233
  172. package/src/specs/openrouter.simple.test.js +0 -202
  173. package/src/specs/prune.test.js +0 -733
  174. package/src/specs/reasoning.test.js +0 -144
  175. package/src/specs/spec.utils.js +0 -4
  176. package/src/specs/thinking-handoff.test.js +0 -486
  177. package/src/specs/thinking-prune.test.js +0 -600
  178. package/src/specs/token-distribution-edge-case.test.js +0 -246
  179. package/src/specs/token-memoization.test.js +0 -32
  180. package/src/specs/tokens.test.js +0 -49
  181. package/src/specs/tool-error.test.js +0 -139
  182. package/src/splitStream.js +0 -204
  183. package/src/splitStream.test.js +0 -504
  184. package/src/stream.js +0 -650
  185. package/src/stream.test.js +0 -225
  186. package/src/test/mockTools.js +0 -340
  187. package/src/tools/BrowserTools.js +0 -245
  188. package/src/tools/Calculator.js +0 -38
  189. package/src/tools/Calculator.test.js +0 -225
  190. package/src/tools/CodeExecutor.js +0 -233
  191. package/src/tools/ProgrammaticToolCalling.js +0 -602
  192. package/src/tools/StreamingToolCallBuffer.js +0 -179
  193. package/src/tools/ToolNode.js +0 -930
  194. package/src/tools/ToolSearch.js +0 -904
  195. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  196. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  197. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  198. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  199. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  200. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  201. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  202. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  203. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  204. package/src/tools/__tests__/handlers.test.js +0 -799
  205. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  206. package/src/tools/handlers.js +0 -306
  207. package/src/tools/schema.js +0 -25
  208. package/src/tools/search/anthropic.js +0 -34
  209. package/src/tools/search/content.js +0 -116
  210. package/src/tools/search/content.test.js +0 -133
  211. package/src/tools/search/firecrawl.js +0 -173
  212. package/src/tools/search/format.js +0 -198
  213. package/src/tools/search/highlights.js +0 -241
  214. package/src/tools/search/index.js +0 -3
  215. package/src/tools/search/jina-reranker.test.js +0 -106
  216. package/src/tools/search/rerankers.js +0 -165
  217. package/src/tools/search/schema.js +0 -102
  218. package/src/tools/search/search.js +0 -561
  219. package/src/tools/search/serper-scraper.js +0 -126
  220. package/src/tools/search/test.js +0 -129
  221. package/src/tools/search/tool.js +0 -453
  222. package/src/tools/search/types.js +0 -2
  223. package/src/tools/search/utils.js +0 -59
  224. package/src/types/graph.js +0 -24
  225. package/src/types/graph.test.js +0 -192
  226. package/src/types/index.js +0 -7
  227. package/src/types/llm.js +0 -2
  228. package/src/types/messages.js +0 -2
  229. package/src/types/run.js +0 -2
  230. package/src/types/stream.js +0 -2
  231. package/src/types/tools.js +0 -2
  232. package/src/utils/contextAnalytics.js +0 -79
  233. package/src/utils/contextAnalytics.test.js +0 -166
  234. package/src/utils/events.js +0 -26
  235. package/src/utils/graph.js +0 -11
  236. package/src/utils/handlers.js +0 -65
  237. package/src/utils/index.js +0 -10
  238. package/src/utils/llm.js +0 -21
  239. package/src/utils/llmConfig.js +0 -205
  240. package/src/utils/logging.js +0 -37
  241. package/src/utils/misc.js +0 -51
  242. package/src/utils/run.js +0 -69
  243. package/src/utils/schema.js +0 -21
  244. package/src/utils/title.js +0 -119
  245. package/src/utils/tokens.js +0 -92
  246. package/src/utils/toonFormat.js +0 -379
@@ -1,58 +0,0 @@
1
- export const taskManagerPrompt = `You are a Task Manager responsible for efficiently coordinating a team of specialized workers: {members}. Your PRIMARY and SOLE OBJECTIVE is to fulfill the user's specific request as quickly and effectively as possible.
2
-
3
- CRITICAL GUIDELINES:
4
- 1. The user's request is your CHIEF CONCERN. Every action must directly contribute to fulfilling this request.
5
- 2. Aim to complete the entire task in NO MORE THAN 2-3 TURNS, unless explicitly instructed otherwise.
6
- 3. Eliminate all superfluous activity. Each task must be essential to achieving the user's goal.
7
- 4. Assign no more than 5 tasks per turn, and only if absolutely necessary.
8
- 5. Be concise and direct in your task assignments.
9
- 6. End the process IMMEDIATELY once the user's request is fulfilled by setting 'end' to true and assigning no new tasks.
10
-
11
- Your responsibilities:
12
- 1. Analyze the user's request and break it down into the minimum necessary subtasks.
13
- 2. Assign these essential tasks to the most appropriate team members based on their skills and tools.
14
- 3. Prioritize tasks to ensure the most efficient path to completion.
15
- 4. Continuously evaluate if the user's request has been fully addressed.
16
- 5. End the process IMMEDIATELY once the user's request is fulfilled.
17
-
18
- Task Assignment Guidelines:
19
- - Assign only the most crucial tasks required to meet the user's needs.
20
- - Multiple tasks can be assigned to the same team member if it improves efficiency.
21
- - Always specify the tool to use if applicable.
22
- - Consider task dependencies to minimize the number of turns.
23
-
24
- After each round:
25
- - Critically assess if the user's request has been fully addressed.
26
- - If more work is genuinely needed, assign only the most essential remaining tasks.
27
- - If the user's request has been fulfilled or can be fulfilled with the results at hand, set 'end' to true and assign no new tasks.
28
-
29
- REMEMBER: Your success is measured by how quickly and effectively you fulfill the user's request, not by the number of tasks assigned or turns taken. Excessive deliberation or unnecessary tasks are counterproductive. Focus solely on the user's needs and conclude the process as soon as those needs are met.`;
30
- export const assignTasksFunctionDescription = 'Assign the minimum necessary tasks to team members to fulfill the user\'s request as quickly as possible. Assign up to 5 tasks maximum per turn, only if absolutely necessary. Each task must specify the team member, a concise description, and the tool to use if applicable.';
31
- export const assignTasksFunctionParameters = {
32
- type: 'object',
33
- properties: {
34
- tasks: {
35
- type: 'array',
36
- items: {
37
- type: 'object',
38
- properties: {
39
- member: { type: 'string', description: 'Name of the team member assigned to the task' },
40
- description: { type: 'string', description: 'Concise description of the essential task to be performed' },
41
- tool: { type: 'string', description: 'Specific tool to be used for the task, if applicable' },
42
- },
43
- required: ['member', 'description'],
44
- },
45
- description: 'List of essential tasks to be assigned, maximum 5 tasks per turn.',
46
- },
47
- },
48
- required: ['tasks'],
49
- };
50
- export const endProcessFunctionDescription = 'End the process when the user\'s request has been fulfilled.';
51
- export const endProcessFunctionParameters = {
52
- type: 'object',
53
- properties: {
54
- reason: { type: 'string', description: 'Brief explanation of why the process is ending' },
55
- },
56
- required: ['reason'],
57
- };
58
- //# sourceMappingURL=taskmanager.js.map
package/src/run.js DELETED
@@ -1,427 +0,0 @@
1
- // src/run.ts
2
- import './instrumentation';
3
- import { ObservabilityCallbackHandler } from '@illuma-ai/observability-langchain';
4
- import { PromptTemplate } from '@langchain/core/prompts';
5
- import { RunnableLambda } from '@langchain/core/runnables';
6
- import { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';
7
- import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
8
- import { createCompletionTitleRunnable, createTitleRunnable, } from '@/utils/title';
9
- import { createTokenCounter, encodingForModel } from '@/utils/tokens';
10
- import { GraphEvents, Callback, TitleMethod } from '@/common';
11
- import { MultiAgentGraph } from '@/graphs/MultiAgentGraph';
12
- import { StandardGraph } from '@/graphs/Graph';
13
- import { HandlerRegistry } from '@/events';
14
- import { isOpenAILike } from '@/utils/llm';
15
- import { isPresent } from '@/utils/misc';
16
- export const defaultOmitOptions = new Set([
17
- 'stream',
18
- 'thinking',
19
- 'streaming',
20
- 'maxTokens',
21
- 'clientOptions',
22
- 'thinkingConfig',
23
- 'thinkingBudget',
24
- 'includeThoughts',
25
- 'maxOutputTokens',
26
- 'additionalModelRequestFields',
27
- ]);
28
- export class Run {
29
- id;
30
- tokenCounter;
31
- handlerRegistry;
32
- indexTokenCountMap;
33
- graphRunnable;
34
- Graph;
35
- returnContent = false;
36
- skipCleanup = false;
37
- /**
38
- * Reference to the observability callback handler, stored so that
39
- * guardrail traces can be appended after processStream() completes.
40
- */
41
- observabilityHandler;
42
- /**
43
- * Guardrail results collected before processStream() starts (e.g., input moderation).
44
- * These are flushed to the trace once the handler creates the root trace.
45
- */
46
- pendingGuardrails = [];
47
- constructor(config) {
48
- const runId = config.runId ?? '';
49
- if (!runId) {
50
- throw new Error('Run ID not provided');
51
- }
52
- this.id = runId;
53
- this.tokenCounter = config.tokenCounter;
54
- this.indexTokenCountMap = config.indexTokenCountMap;
55
- const handlerRegistry = new HandlerRegistry();
56
- if (config.customHandlers) {
57
- for (const [eventType, handler] of Object.entries(config.customHandlers)) {
58
- handlerRegistry.register(eventType, handler);
59
- }
60
- }
61
- this.handlerRegistry = handlerRegistry;
62
- if (!config.graphConfig) {
63
- throw new Error('Graph config not provided');
64
- }
65
- /** Handle different graph types */
66
- if (config.graphConfig.type === 'multi-agent') {
67
- this.graphRunnable = this.createMultiAgentGraph(config.graphConfig);
68
- if (this.Graph) {
69
- this.Graph.handlerRegistry = handlerRegistry;
70
- }
71
- }
72
- else {
73
- /** Default to legacy graph for 'standard' or undefined type */
74
- this.graphRunnable = this.createLegacyGraph(config.graphConfig);
75
- if (this.Graph) {
76
- this.Graph.compileOptions =
77
- config.graphConfig.compileOptions ?? this.Graph.compileOptions;
78
- this.Graph.handlerRegistry = handlerRegistry;
79
- }
80
- }
81
- this.returnContent = config.returnContent ?? false;
82
- this.skipCleanup = config.skipCleanup ?? false;
83
- }
84
- createLegacyGraph(config) {
85
- let agentConfig;
86
- let signal;
87
- /** Check if this is a multi-agent style config (has agents array) */
88
- if ('agents' in config && Array.isArray(config.agents)) {
89
- if (config.agents.length === 0) {
90
- throw new Error('At least one agent must be provided');
91
- }
92
- agentConfig = config.agents[0];
93
- signal = config.signal;
94
- }
95
- else {
96
- /** Legacy path: build agent config from llmConfig */
97
- const { type: _type, llmConfig, signal: legacySignal, tools = [], ...agentInputs } = config;
98
- const { provider, ...clientOptions } = llmConfig;
99
- agentConfig = {
100
- ...agentInputs,
101
- tools,
102
- provider,
103
- clientOptions,
104
- agentId: 'default',
105
- };
106
- signal = legacySignal;
107
- }
108
- const standardGraph = new StandardGraph({
109
- signal,
110
- runId: this.id,
111
- agents: [agentConfig],
112
- tokenCounter: this.tokenCounter,
113
- indexTokenCountMap: this.indexTokenCountMap,
114
- });
115
- /** Propagate compile options from graph config */
116
- standardGraph.compileOptions = config.compileOptions;
117
- this.Graph = standardGraph;
118
- return standardGraph.createWorkflow();
119
- }
120
- createMultiAgentGraph(config) {
121
- const { agents, edges, compileOptions } = config;
122
- const multiAgentGraph = new MultiAgentGraph({
123
- runId: this.id,
124
- agents,
125
- edges,
126
- tokenCounter: this.tokenCounter,
127
- indexTokenCountMap: this.indexTokenCountMap,
128
- });
129
- if (compileOptions != null) {
130
- multiAgentGraph.compileOptions = compileOptions;
131
- }
132
- this.Graph = multiAgentGraph;
133
- return multiAgentGraph.createWorkflow();
134
- }
135
- static async create(config) {
136
- /** Create tokenCounter if indexTokenCountMap is provided but tokenCounter is not */
137
- if (config.indexTokenCountMap && !config.tokenCounter) {
138
- const gc = config.graphConfig;
139
- const clientOpts = 'agents' in gc ? gc.agents[0]?.clientOptions : gc.clientOptions;
140
- const model = clientOpts?.model ?? '';
141
- config.tokenCounter = await createTokenCounter(encodingForModel(model));
142
- }
143
- return new Run(config);
144
- }
145
- getRunMessages() {
146
- if (!this.Graph) {
147
- throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');
148
- }
149
- return this.Graph.getRunMessages();
150
- }
151
- /**
152
- * Manually trigger cleanup of heavy state (messages, config, etc.).
153
- * Call this after all continuations are complete when using skipCleanup=true.
154
- */
155
- clearState() {
156
- if (this.Graph) {
157
- this.Graph.clearHeavyState();
158
- }
159
- }
160
- /**
161
- * Returns the normalized finish/stop reason from the last LLM invocation.
162
- * Delegates to the underlying Graph instance.
163
- */
164
- getLastFinishReason() {
165
- if (this.Graph && 'getLastFinishReason' in this.Graph) {
166
- return this.Graph.getLastFinishReason();
167
- }
168
- return undefined;
169
- }
170
- /**
171
- * Returns the ID of the last agent that produced output in a multi-agent graph.
172
- * Used by auto-continuation to determine which agent's context to preserve
173
- * when a response is truncated after an agent handoff.
174
- * Returns undefined for single-agent graphs.
175
- */
176
- getLastActiveAgentId() {
177
- if (this.Graph && this.Graph instanceof MultiAgentGraph) {
178
- return this.Graph.getLastActiveAgentId();
179
- }
180
- return undefined;
181
- }
182
- /**
183
- * Trace a guardrail execution as part of the current observability trace.
184
- *
185
- * For **input guardrails** (before processStream): data is queued as pending
186
- * and flushed once the trace is created during processStream().
187
- *
188
- * For **output guardrails** (after processStream): data is sent immediately
189
- * to the existing trace.
190
- *
191
- * @param data - Guardrail execution result from ranger's guardrail service
192
- * @returns The observation ID if sent immediately, or null if queued/no handler
193
- */
194
- traceGuardrail(data) {
195
- if (this.observabilityHandler) {
196
- return this.observabilityHandler.traceGuardrail(data);
197
- }
198
- // No handler yet — queue for later (input guardrail before processStream)
199
- this.pendingGuardrails.push(data);
200
- return null;
201
- }
202
- /**
203
- * Returns the observability trace ID for this run, or null if observability
204
- * is not enabled or no trace has been created yet.
205
- */
206
- getTraceId() {
207
- return this.observabilityHandler?.getTraceId() ?? null;
208
- }
209
- /**
210
- * Creates a custom event callback handler that intercepts custom events
211
- * and processes them through our handler registry instead of EventStreamCallbackHandler
212
- */
213
- createCustomEventCallback() {
214
- return async (eventName, data, runId, tags, metadata) => {
215
- const handler = this.handlerRegistry?.getHandler(eventName);
216
- if (handler && this.Graph) {
217
- return await handler.handle(eventName, data, metadata, this.Graph);
218
- }
219
- };
220
- }
221
- async processStream(inputs, config, streamOptions) {
222
- if (this.graphRunnable == null) {
223
- throw new Error('Run not initialized. Make sure to use Run.create() to instantiate the Run.');
224
- }
225
- if (!this.Graph) {
226
- throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');
227
- }
228
- this.Graph.resetValues(streamOptions?.keepContent);
229
- /** Custom event callback to intercept and handle custom events */
230
- const customEventCallback = this.createCustomEventCallback();
231
- const baseCallbacks = config.callbacks ?? [];
232
- const streamCallbacks = streamOptions?.callbacks
233
- ? this.getCallbacks(streamOptions.callbacks)
234
- : [];
235
- const customHandler = BaseCallbackHandler.fromMethods({
236
- [Callback.CUSTOM_EVENT]: customEventCallback,
237
- });
238
- customHandler.awaitHandlers = true;
239
- config.callbacks = baseCallbacks
240
- .concat(streamCallbacks)
241
- .concat(customHandler);
242
- const secretKey = process.env.ILLUMA_SECRET_KEY ?? process.env.LANGFUSE_SECRET_KEY;
243
- const publicKey = process.env.ILLUMA_PUBLIC_KEY ?? process.env.LANGFUSE_PUBLIC_KEY;
244
- const baseUrl = process.env.ILLUMA_BASE_URL ?? process.env.LANGFUSE_BASE_URL;
245
- if (isPresent(secretKey) && isPresent(publicKey) && isPresent(baseUrl)) {
246
- const userId = config.configurable?.user_id;
247
- const sessionId = config.configurable?.thread_id;
248
- const handler = new ObservabilityCallbackHandler({
249
- clientOptions: { publicKey, secretKey, baseUrl },
250
- userId,
251
- sessionId,
252
- metadata: {
253
- messageId: this.id,
254
- parentMessageId: config.configurable?.requestBody?.parentMessageId,
255
- },
256
- environment: process.env.ILLUMA_ENVIRONMENT ?? process.env.LANGFUSE_TRACING_ENVIRONMENT ?? process.env.NODE_ENV,
257
- });
258
- this.observabilityHandler = handler;
259
- config.callbacks = (config.callbacks ?? []).concat([handler]);
260
- }
261
- if (!this.id) {
262
- throw new Error('Run ID not provided');
263
- }
264
- config.run_id = this.id;
265
- config.configurable = Object.assign(config.configurable ?? {}, {
266
- run_id: this.id,
267
- });
268
- const stream = this.graphRunnable.streamEvents(inputs, config, {
269
- raiseError: true,
270
- /**
271
- * Prevent EventStreamCallbackHandler from processing custom events.
272
- * Custom events are already handled via our createCustomEventCallback()
273
- * which routes them through the handlerRegistry.
274
- * Without this flag, EventStreamCallbackHandler throws errors when
275
- * custom events are dispatched for run IDs not in its internal map
276
- * (due to timing issues in parallel execution or after run cleanup).
277
- */
278
- ignoreCustomEvent: true,
279
- });
280
- for await (const event of stream) {
281
- const { data, metadata, ...info } = event;
282
- const eventName = info.event;
283
- /** Skip custom events as they're handled by our callback */
284
- if (eventName === GraphEvents.ON_CUSTOM_EVENT) {
285
- continue;
286
- }
287
- const handler = this.handlerRegistry?.getHandler(eventName);
288
- if (handler) {
289
- await handler.handle(eventName, data, metadata, this.Graph);
290
- }
291
- }
292
- // Flush any guardrails that were collected before processStream()
293
- // (e.g., input moderation). Now the trace exists so they can be attached.
294
- if (this.observabilityHandler && this.pendingGuardrails.length > 0) {
295
- for (const guardrail of this.pendingGuardrails) {
296
- this.observabilityHandler.traceGuardrail(guardrail);
297
- }
298
- this.pendingGuardrails = [];
299
- }
300
- /**
301
- * Break the reference chain that keeps heavy data alive via
302
- * LangGraph's internal `__pregel_scratchpad.currentTaskInput` →
303
- * `@langchain/core` `RunTree.extra[lc:child_config]` →
304
- * Node.js `AsyncLocalStorage` context captured by timers/promises.
305
- *
306
- * Without this, base64-encoded images/PDFs in message content remain
307
- * reachable from lingering `Timeout` handles until GC runs.
308
- */
309
- if (!this.skipCleanup) {
310
- if (config.configurable != null) {
311
- for (const key of Object.getOwnPropertySymbols(config.configurable)) {
312
- const val = config.configurable[key];
313
- if (val != null &&
314
- typeof val === 'object' &&
315
- 'currentTaskInput' in val) {
316
- val.currentTaskInput = undefined;
317
- }
318
- delete config.configurable[key];
319
- }
320
- config.configurable = undefined;
321
- }
322
- config.callbacks = undefined;
323
- }
324
- const result = this.returnContent
325
- ? this.Graph.getContentParts()
326
- : undefined;
327
- if (!this.skipCleanup) {
328
- this.Graph.clearHeavyState();
329
- }
330
- return result;
331
- }
332
- createSystemCallback(clientCallbacks, key) {
333
- return ((...args) => {
334
- const clientCallback = clientCallbacks[key];
335
- if (clientCallback && this.Graph) {
336
- clientCallback(this.Graph, ...args);
337
- }
338
- });
339
- }
340
- getCallbacks(clientCallbacks) {
341
- return {
342
- [Callback.TOOL_ERROR]: this.createSystemCallback(clientCallbacks, Callback.TOOL_ERROR),
343
- [Callback.TOOL_START]: this.createSystemCallback(clientCallbacks, Callback.TOOL_START),
344
- [Callback.TOOL_END]: this.createSystemCallback(clientCallbacks, Callback.TOOL_END),
345
- };
346
- }
347
- async generateTitle({ provider, inputText, contentParts, titlePrompt, clientOptions, chainOptions, skipLanguage, titleMethod = TitleMethod.COMPLETION, titlePromptTemplate, }) {
348
- const titleSecretKey = process.env.ILLUMA_SECRET_KEY ?? process.env.LANGFUSE_SECRET_KEY;
349
- const titlePublicKey = process.env.ILLUMA_PUBLIC_KEY ?? process.env.LANGFUSE_PUBLIC_KEY;
350
- const titleBaseUrl = process.env.ILLUMA_BASE_URL ?? process.env.LANGFUSE_BASE_URL;
351
- if (chainOptions != null &&
352
- isPresent(titleSecretKey) && isPresent(titlePublicKey) && isPresent(titleBaseUrl)) {
353
- const userId = chainOptions.configurable?.user_id;
354
- const sessionId = chainOptions.configurable?.thread_id;
355
- const handler = new ObservabilityCallbackHandler({
356
- clientOptions: { publicKey: titlePublicKey, secretKey: titleSecretKey, baseUrl: titleBaseUrl },
357
- userId,
358
- sessionId,
359
- metadata: {
360
- messageId: 'title-' + this.id,
361
- },
362
- environment: process.env.ILLUMA_ENVIRONMENT ?? process.env.LANGFUSE_TRACING_ENVIRONMENT ?? process.env.NODE_ENV,
363
- });
364
- chainOptions.callbacks = (chainOptions.callbacks ?? []).concat([handler]);
365
- }
366
- const convoTemplate = PromptTemplate.fromTemplate(titlePromptTemplate ?? 'User: {input}\nAI: {output}');
367
- const response = contentParts
368
- .map((part) => {
369
- if (part?.type === 'text')
370
- return part.text;
371
- return '';
372
- })
373
- .join('\n');
374
- const model = this.Graph?.getNewModel({
375
- provider,
376
- clientOptions,
377
- });
378
- if (!model) {
379
- return { language: '', title: '' };
380
- }
381
- if (isOpenAILike(provider) &&
382
- (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {
383
- model.temperature = clientOptions
384
- ?.temperature;
385
- model.topP = clientOptions
386
- ?.topP;
387
- model.frequencyPenalty = clientOptions?.frequencyPenalty;
388
- model.presencePenalty = clientOptions?.presencePenalty;
389
- model.n = clientOptions
390
- ?.n;
391
- }
392
- const convoToTitleInput = new RunnableLambda({
393
- func: (promptValue) => ({
394
- convo: promptValue.value,
395
- inputText,
396
- skipLanguage,
397
- }),
398
- }).withConfig({ runName: 'ConvoTransform' });
399
- const titleChain = titleMethod === TitleMethod.COMPLETION
400
- ? await createCompletionTitleRunnable(model, titlePrompt)
401
- : await createTitleRunnable(model, titlePrompt);
402
- /** Pipes `convoTemplate` -> `transformer` -> `titleChain` */
403
- const fullChain = convoTemplate
404
- .withConfig({ runName: 'ConvoTemplate' })
405
- .pipe(convoToTitleInput)
406
- .pipe(titleChain)
407
- .withConfig({ runName: 'TitleChain' });
408
- const invokeConfig = Object.assign({}, chainOptions, {
409
- run_id: this.id,
410
- runId: this.id,
411
- });
412
- try {
413
- return await fullChain.invoke({ input: inputText, output: response }, invokeConfig);
414
- }
415
- catch (_e) {
416
- // Fallback: strip callbacks to avoid EventStream tracer errors in certain environments
417
- // But preserve observability handler if it exists
418
- const illumaHandler = invokeConfig.callbacks?.find((cb) => cb instanceof ObservabilityCallbackHandler);
419
- const { callbacks: _cb, ...rest } = invokeConfig;
420
- const safeConfig = Object.assign({}, rest, {
421
- callbacks: illumaHandler ? [illumaHandler] : [],
422
- });
423
- return await fullChain.invoke({ input: inputText, output: response }, safeConfig);
424
- }
425
- }
426
- }
427
- //# sourceMappingURL=run.js.map
@@ -1,3 +0,0 @@
1
- // src/schemas/index.ts
2
- export * from './validate';
3
- //# sourceMappingURL=index.js.map