illuma-agents 1.0.2 → 1.0.3

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 (225) hide show
  1. package/LICENSE +25 -21
  2. package/dist/cjs/agents/AgentContext.cjs +222 -0
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -0
  4. package/dist/cjs/common/enum.cjs +7 -6
  5. package/dist/cjs/common/enum.cjs.map +1 -1
  6. package/dist/cjs/events.cjs +7 -5
  7. package/dist/cjs/events.cjs.map +1 -1
  8. package/dist/cjs/graphs/Graph.cjs +328 -207
  9. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  10. package/dist/cjs/graphs/MultiAgentGraph.cjs +507 -0
  11. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -0
  12. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  13. package/dist/cjs/llm/google/index.cjs.map +1 -1
  14. package/dist/cjs/llm/ollama/index.cjs.map +1 -1
  15. package/dist/cjs/llm/openai/index.cjs +35 -0
  16. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  17. package/dist/cjs/llm/openai/utils/index.cjs +3 -1
  18. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  19. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  20. package/dist/cjs/llm/providers.cjs +0 -2
  21. package/dist/cjs/llm/providers.cjs.map +1 -1
  22. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  23. package/dist/cjs/main.cjs +12 -1
  24. package/dist/cjs/main.cjs.map +1 -1
  25. package/dist/cjs/messages/cache.cjs +123 -0
  26. package/dist/cjs/messages/cache.cjs.map +1 -0
  27. package/dist/cjs/messages/content.cjs +53 -0
  28. package/dist/cjs/messages/content.cjs.map +1 -0
  29. package/dist/cjs/messages/format.cjs +17 -29
  30. package/dist/cjs/messages/format.cjs.map +1 -1
  31. package/dist/cjs/run.cjs +119 -74
  32. package/dist/cjs/run.cjs.map +1 -1
  33. package/dist/cjs/stream.cjs +77 -73
  34. package/dist/cjs/stream.cjs.map +1 -1
  35. package/dist/cjs/tools/Calculator.cjs +45 -0
  36. package/dist/cjs/tools/Calculator.cjs.map +1 -0
  37. package/dist/cjs/tools/CodeExecutor.cjs +22 -22
  38. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  39. package/dist/cjs/tools/ToolNode.cjs +5 -3
  40. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  41. package/dist/cjs/tools/handlers.cjs +20 -20
  42. package/dist/cjs/tools/handlers.cjs.map +1 -1
  43. package/dist/cjs/utils/events.cjs +31 -0
  44. package/dist/cjs/utils/events.cjs.map +1 -0
  45. package/dist/cjs/utils/handlers.cjs +70 -0
  46. package/dist/cjs/utils/handlers.cjs.map +1 -0
  47. package/dist/cjs/utils/tokens.cjs +54 -7
  48. package/dist/cjs/utils/tokens.cjs.map +1 -1
  49. package/dist/esm/agents/AgentContext.mjs +220 -0
  50. package/dist/esm/agents/AgentContext.mjs.map +1 -0
  51. package/dist/esm/common/enum.mjs +7 -6
  52. package/dist/esm/common/enum.mjs.map +1 -1
  53. package/dist/esm/events.mjs +7 -5
  54. package/dist/esm/events.mjs.map +1 -1
  55. package/dist/esm/graphs/Graph.mjs +330 -209
  56. package/dist/esm/graphs/Graph.mjs.map +1 -1
  57. package/dist/esm/graphs/MultiAgentGraph.mjs +505 -0
  58. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -0
  59. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  60. package/dist/esm/llm/google/index.mjs.map +1 -1
  61. package/dist/esm/llm/ollama/index.mjs.map +1 -1
  62. package/dist/esm/llm/openai/index.mjs +35 -0
  63. package/dist/esm/llm/openai/index.mjs.map +1 -1
  64. package/dist/esm/llm/openai/utils/index.mjs +3 -1
  65. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  66. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  67. package/dist/esm/llm/providers.mjs +0 -2
  68. package/dist/esm/llm/providers.mjs.map +1 -1
  69. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  70. package/dist/esm/main.mjs +7 -2
  71. package/dist/esm/main.mjs.map +1 -1
  72. package/dist/esm/messages/cache.mjs +120 -0
  73. package/dist/esm/messages/cache.mjs.map +1 -0
  74. package/dist/esm/messages/content.mjs +51 -0
  75. package/dist/esm/messages/content.mjs.map +1 -0
  76. package/dist/esm/messages/format.mjs +18 -29
  77. package/dist/esm/messages/format.mjs.map +1 -1
  78. package/dist/esm/run.mjs +119 -74
  79. package/dist/esm/run.mjs.map +1 -1
  80. package/dist/esm/stream.mjs +77 -73
  81. package/dist/esm/stream.mjs.map +1 -1
  82. package/dist/esm/tools/Calculator.mjs +24 -0
  83. package/dist/esm/tools/Calculator.mjs.map +1 -0
  84. package/dist/esm/tools/CodeExecutor.mjs +22 -22
  85. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  86. package/dist/esm/tools/ToolNode.mjs +5 -3
  87. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  88. package/dist/esm/tools/handlers.mjs +20 -20
  89. package/dist/esm/tools/handlers.mjs.map +1 -1
  90. package/dist/esm/utils/events.mjs +29 -0
  91. package/dist/esm/utils/events.mjs.map +1 -0
  92. package/dist/esm/utils/handlers.mjs +68 -0
  93. package/dist/esm/utils/handlers.mjs.map +1 -0
  94. package/dist/esm/utils/tokens.mjs +54 -8
  95. package/dist/esm/utils/tokens.mjs.map +1 -1
  96. package/dist/types/agents/AgentContext.d.ts +94 -0
  97. package/dist/types/common/enum.d.ts +9 -7
  98. package/dist/types/events.d.ts +3 -3
  99. package/dist/types/graphs/Graph.d.ts +60 -66
  100. package/dist/types/graphs/MultiAgentGraph.d.ts +47 -0
  101. package/dist/types/graphs/index.d.ts +1 -0
  102. package/dist/types/index.d.ts +1 -0
  103. package/dist/types/llm/openai/index.d.ts +10 -0
  104. package/dist/types/messages/cache.d.ts +20 -0
  105. package/dist/types/messages/content.d.ts +7 -0
  106. package/dist/types/messages/format.d.ts +1 -7
  107. package/dist/types/messages/index.d.ts +2 -0
  108. package/dist/types/messages/reducer.d.ts +9 -0
  109. package/dist/types/run.d.ts +16 -10
  110. package/dist/types/stream.d.ts +4 -3
  111. package/dist/types/tools/Calculator.d.ts +8 -0
  112. package/dist/types/tools/ToolNode.d.ts +1 -1
  113. package/dist/types/tools/handlers.d.ts +9 -7
  114. package/dist/types/tools/search/tool.d.ts +4 -4
  115. package/dist/types/types/graph.d.ts +124 -11
  116. package/dist/types/types/llm.d.ts +13 -9
  117. package/dist/types/types/messages.d.ts +4 -0
  118. package/dist/types/types/run.d.ts +46 -8
  119. package/dist/types/types/stream.d.ts +3 -2
  120. package/dist/types/utils/events.d.ts +6 -0
  121. package/dist/types/utils/handlers.d.ts +34 -0
  122. package/dist/types/utils/index.d.ts +1 -0
  123. package/dist/types/utils/tokens.d.ts +24 -0
  124. package/package.json +162 -145
  125. package/src/agents/AgentContext.ts +323 -0
  126. package/src/common/enum.ts +177 -176
  127. package/src/events.ts +197 -191
  128. package/src/graphs/Graph.ts +1058 -846
  129. package/src/graphs/MultiAgentGraph.ts +598 -0
  130. package/src/graphs/index.ts +2 -1
  131. package/src/index.ts +25 -24
  132. package/src/llm/anthropic/index.ts +413 -413
  133. package/src/llm/google/index.ts +222 -222
  134. package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -88
  135. package/src/llm/ollama/index.ts +92 -92
  136. package/src/llm/openai/index.ts +894 -853
  137. package/src/llm/openai/utils/index.ts +920 -918
  138. package/src/llm/openrouter/index.ts +60 -60
  139. package/src/llm/providers.ts +55 -57
  140. package/src/llm/vertexai/index.ts +360 -360
  141. package/src/messages/cache.test.ts +461 -0
  142. package/src/messages/cache.ts +151 -0
  143. package/src/messages/content.test.ts +362 -0
  144. package/src/messages/content.ts +63 -0
  145. package/src/messages/format.ts +611 -625
  146. package/src/messages/formatAgentMessages.test.ts +1144 -917
  147. package/src/messages/index.ts +6 -4
  148. package/src/messages/reducer.ts +80 -0
  149. package/src/run.ts +447 -381
  150. package/src/scripts/abort.ts +157 -138
  151. package/src/scripts/ant_web_search.ts +158 -158
  152. package/src/scripts/cli.ts +172 -167
  153. package/src/scripts/cli2.ts +133 -125
  154. package/src/scripts/cli3.ts +184 -178
  155. package/src/scripts/cli4.ts +191 -184
  156. package/src/scripts/cli5.ts +191 -184
  157. package/src/scripts/code_exec.ts +213 -214
  158. package/src/scripts/code_exec_simple.ts +147 -129
  159. package/src/scripts/content.ts +138 -120
  160. package/src/scripts/handoff-test.ts +135 -0
  161. package/src/scripts/multi-agent-chain.ts +278 -0
  162. package/src/scripts/multi-agent-conditional.ts +220 -0
  163. package/src/scripts/multi-agent-document-review-chain.ts +197 -0
  164. package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
  165. package/src/scripts/multi-agent-parallel.ts +343 -0
  166. package/src/scripts/multi-agent-sequence.ts +212 -0
  167. package/src/scripts/multi-agent-supervisor.ts +364 -0
  168. package/src/scripts/multi-agent-test.ts +186 -0
  169. package/src/scripts/search.ts +146 -150
  170. package/src/scripts/simple.ts +225 -225
  171. package/src/scripts/stream.ts +140 -122
  172. package/src/scripts/test-custom-prompt-key.ts +145 -0
  173. package/src/scripts/test-handoff-input.ts +170 -0
  174. package/src/scripts/test-multi-agent-list-handoff.ts +261 -0
  175. package/src/scripts/test-tools-before-handoff.ts +222 -0
  176. package/src/scripts/tools.ts +153 -155
  177. package/src/specs/agent-handoffs.test.ts +889 -0
  178. package/src/specs/anthropic.simple.test.ts +320 -317
  179. package/src/specs/azure.simple.test.ts +325 -316
  180. package/src/specs/openai.simple.test.ts +311 -316
  181. package/src/specs/openrouter.simple.test.ts +107 -0
  182. package/src/specs/prune.test.ts +758 -763
  183. package/src/specs/reasoning.test.ts +201 -165
  184. package/src/specs/thinking-prune.test.ts +769 -703
  185. package/src/specs/token-memoization.test.ts +39 -0
  186. package/src/stream.ts +664 -651
  187. package/src/tools/Calculator.test.ts +278 -0
  188. package/src/tools/Calculator.ts +25 -0
  189. package/src/tools/CodeExecutor.ts +220 -220
  190. package/src/tools/ToolNode.ts +170 -170
  191. package/src/tools/handlers.ts +341 -336
  192. package/src/types/graph.ts +372 -185
  193. package/src/types/llm.ts +141 -140
  194. package/src/types/messages.ts +4 -0
  195. package/src/types/run.ts +128 -89
  196. package/src/types/stream.ts +401 -400
  197. package/src/utils/events.ts +32 -0
  198. package/src/utils/handlers.ts +107 -0
  199. package/src/utils/index.ts +6 -5
  200. package/src/utils/llmConfig.ts +183 -183
  201. package/src/utils/tokens.ts +129 -70
  202. package/dist/types/scripts/abort.d.ts +0 -1
  203. package/dist/types/scripts/ant_web_search.d.ts +0 -1
  204. package/dist/types/scripts/args.d.ts +0 -7
  205. package/dist/types/scripts/caching.d.ts +0 -1
  206. package/dist/types/scripts/cli.d.ts +0 -1
  207. package/dist/types/scripts/cli2.d.ts +0 -1
  208. package/dist/types/scripts/cli3.d.ts +0 -1
  209. package/dist/types/scripts/cli4.d.ts +0 -1
  210. package/dist/types/scripts/cli5.d.ts +0 -1
  211. package/dist/types/scripts/code_exec.d.ts +0 -1
  212. package/dist/types/scripts/code_exec_files.d.ts +0 -1
  213. package/dist/types/scripts/code_exec_simple.d.ts +0 -1
  214. package/dist/types/scripts/content.d.ts +0 -1
  215. package/dist/types/scripts/empty_input.d.ts +0 -1
  216. package/dist/types/scripts/image.d.ts +0 -1
  217. package/dist/types/scripts/memory.d.ts +0 -1
  218. package/dist/types/scripts/search.d.ts +0 -1
  219. package/dist/types/scripts/simple.d.ts +0 -1
  220. package/dist/types/scripts/stream.d.ts +0 -1
  221. package/dist/types/scripts/thinking.d.ts +0 -1
  222. package/dist/types/scripts/tools.d.ts +0 -1
  223. package/dist/types/specs/spec.utils.d.ts +0 -1
  224. package/dist/types/tools/example.d.ts +0 -78
  225. package/src/tools/example.ts +0 -129
@@ -0,0 +1,135 @@
1
+ import { config } from 'dotenv';
2
+ config();
3
+
4
+ import { z } from 'zod';
5
+ import { tool } from '@langchain/core/tools';
6
+ import { ChatAnthropic } from '@langchain/anthropic';
7
+ import { createReactAgent } from '@langchain/langgraph/prebuilt';
8
+ import {
9
+ StateGraph,
10
+ MessagesAnnotation,
11
+ Command,
12
+ START,
13
+ getCurrentTaskInput,
14
+ END,
15
+ } from '@langchain/langgraph';
16
+ import { ToolMessage } from '@langchain/core/messages';
17
+
18
+ interface CreateHandoffToolParams {
19
+ agentName: string;
20
+ description?: string;
21
+ }
22
+
23
+ const createHandoffTool = ({
24
+ agentName,
25
+ description,
26
+ }: CreateHandoffToolParams) => {
27
+ const toolName = `transfer_to_${agentName}`;
28
+ const toolDescription = description || `Ask agent '${agentName}' for help`;
29
+
30
+ const handoffTool = tool(
31
+ async (_, config) => {
32
+ const toolMessage = new ToolMessage({
33
+ content: `Successfully transferred to ${agentName}`,
34
+ name: toolName,
35
+ tool_call_id: config.toolCall.id,
36
+ });
37
+
38
+ // inject the current agent state
39
+ const state =
40
+ getCurrentTaskInput() as (typeof MessagesAnnotation)['State'];
41
+ return new Command({
42
+ goto: agentName,
43
+ update: { messages: state.messages.concat(toolMessage) },
44
+ graph: Command.PARENT,
45
+ });
46
+ },
47
+ {
48
+ name: toolName,
49
+ schema: z.object({}),
50
+ description: toolDescription,
51
+ }
52
+ );
53
+
54
+ return handoffTool;
55
+ };
56
+
57
+ const bookHotel = tool(
58
+ async (input: { hotel_name: string }) => {
59
+ return `Successfully booked a stay at ${input.hotel_name}.`;
60
+ },
61
+ {
62
+ name: 'book_hotel',
63
+ description: 'Book a hotel',
64
+ schema: z.object({
65
+ hotel_name: z.string().describe('The name of the hotel to book'),
66
+ }),
67
+ }
68
+ );
69
+
70
+ const bookFlight = tool(
71
+ async (input: { from_airport: string; to_airport: string }) => {
72
+ return `Successfully booked a flight from ${input.from_airport} to ${input.to_airport}.`;
73
+ },
74
+ {
75
+ name: 'book_flight',
76
+ description: 'Book a flight',
77
+ schema: z.object({
78
+ from_airport: z.string().describe('The departure airport code'),
79
+ to_airport: z.string().describe('The arrival airport code'),
80
+ }),
81
+ }
82
+ );
83
+
84
+ const transferToHotelAssistant = createHandoffTool({
85
+ agentName: 'hotel_assistant',
86
+ description: 'Transfer user to the hotel-booking assistant.',
87
+ });
88
+
89
+ const transferToFlightAssistant = createHandoffTool({
90
+ agentName: 'flight_assistant',
91
+ description: 'Transfer user to the flight-booking assistant.',
92
+ });
93
+
94
+ const llm = new ChatAnthropic({
95
+ modelName: 'claude-haiku-4-5',
96
+ apiKey: process.env.ANTHROPIC_API_KEY,
97
+ });
98
+
99
+ const flightAssistant = createReactAgent({
100
+ llm,
101
+ tools: [bookFlight, transferToHotelAssistant],
102
+ prompt: 'You are a flight booking assistant',
103
+ name: 'flight_assistant',
104
+ });
105
+
106
+ const hotelAssistant = createReactAgent({
107
+ llm,
108
+ tools: [bookHotel, transferToFlightAssistant],
109
+ prompt: 'You are a hotel booking assistant',
110
+ name: 'hotel_assistant',
111
+ });
112
+
113
+ const multiAgentGraph = new StateGraph(MessagesAnnotation)
114
+ .addNode('flight_assistant', flightAssistant, {
115
+ ends: ['hotel_assistant', END],
116
+ })
117
+ .addNode('hotel_assistant', hotelAssistant, {
118
+ ends: ['flight_assistant', END],
119
+ })
120
+ .addEdge(START, 'flight_assistant')
121
+ .compile();
122
+
123
+ const stream = await multiAgentGraph.stream({
124
+ messages: [
125
+ {
126
+ role: 'user',
127
+ content: 'book a flight from BOS to JFK and a stay at McKittrick Hotel',
128
+ },
129
+ ],
130
+ });
131
+
132
+ for await (const chunk of stream) {
133
+ console.log(chunk);
134
+ console.log('\n');
135
+ }
@@ -0,0 +1,278 @@
1
+ import { config } from 'dotenv';
2
+ config();
3
+
4
+ import {
5
+ HumanMessage,
6
+ BaseMessage,
7
+ getBufferString,
8
+ } from '@langchain/core/messages';
9
+ import { Run } from '@/run';
10
+ import { Providers, GraphEvents } from '@/common';
11
+ import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
12
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
13
+ import type * as t from '@/types';
14
+
15
+ /**
16
+ * Helper function to create sequential chain edges with buffer string prompts
17
+ *
18
+ * @param agentIds - Array of agent IDs in order of execution
19
+ * @returns Array of edges configured for sequential chain with buffer prompts
20
+ */
21
+ function createSequentialChainEdges(agentIds: string[]): t.GraphEdge[] {
22
+ const edges: t.GraphEdge[] = [];
23
+
24
+ for (let i = 0; i < agentIds.length - 1; i++) {
25
+ const fromAgent = agentIds[i];
26
+ const toAgent = agentIds[i + 1];
27
+
28
+ edges.push({
29
+ from: fromAgent,
30
+ to: toAgent,
31
+ edgeType: 'direct',
32
+ // Use a prompt function to create the buffer string from all previous results
33
+ prompt: (messages: BaseMessage[], startIndex: number) => {
34
+ // Get only the messages from this run (after startIndex)
35
+ const runMessages = messages.slice(startIndex);
36
+
37
+ // Create buffer string from run messages
38
+ const bufferString = getBufferString(runMessages);
39
+
40
+ // Format the prompt for the next agent
41
+ return `Based on the following conversation and analysis from previous agents, please provide your insights:\n\n${bufferString}\n\nPlease add your specific expertise and perspective to this discussion.`;
42
+ },
43
+ // Critical: exclude previous results so only the prompt is passed
44
+ excludeResults: true,
45
+ description: `Sequential chain from ${fromAgent} to ${toAgent}`,
46
+ });
47
+ }
48
+
49
+ return edges;
50
+ }
51
+
52
+ const conversationHistory: BaseMessage[] = [];
53
+
54
+ /**
55
+ * Example of sequential agent chain mimicking the old chain behavior
56
+ *
57
+ * Graph structure:
58
+ * START -> researcher -> analyst -> reviewer -> summarizer -> END
59
+ *
60
+ * Each agent receives a buffer string of all previous results
61
+ */
62
+ async function testSequentialAgentChain() {
63
+ console.log('Testing Sequential Agent Chain (Old Chain Pattern)...\n');
64
+
65
+ // Set up content aggregator
66
+ const { contentParts, aggregateContent } = createContentAggregator();
67
+
68
+ // Define four agents with specific roles
69
+ const agents: t.AgentInputs[] = [
70
+ {
71
+ agentId: 'researcher',
72
+ provider: Providers.ANTHROPIC,
73
+ clientOptions: {
74
+ modelName: 'claude-haiku-4-5',
75
+ apiKey: process.env.ANTHROPIC_API_KEY,
76
+ },
77
+ instructions: `You are a Research Agent specializing in gathering initial information.
78
+ Your role is to:
79
+ 1. Identify key aspects of the user's query
80
+ 2. List important factors to consider
81
+ 3. Provide initial research findings
82
+
83
+ Format your response with clear sections and bullet points.
84
+ Start with "RESEARCH FINDINGS:" and be thorough but concise.`,
85
+ maxContextTokens: 8000,
86
+ },
87
+ {
88
+ agentId: 'analyst',
89
+ provider: Providers.ANTHROPIC,
90
+ clientOptions: {
91
+ modelName: 'claude-haiku-4-5',
92
+ apiKey: process.env.ANTHROPIC_API_KEY,
93
+ },
94
+ instructions: `You are an Analysis Agent that builds upon research findings.
95
+ Your role is to:
96
+ 1. Analyze the research provided by the previous agent
97
+ 2. Identify patterns, risks, and opportunities
98
+ 3. Provide deeper analytical insights
99
+
100
+ Start with "ANALYSIS:" and structure your response with clear categories.
101
+ Reference specific points from the research when relevant.`,
102
+ maxContextTokens: 8000,
103
+ },
104
+ {
105
+ agentId: 'reviewer',
106
+ provider: Providers.ANTHROPIC,
107
+ clientOptions: {
108
+ modelName: 'claude-haiku-4-5',
109
+ apiKey: process.env.ANTHROPIC_API_KEY,
110
+ },
111
+ instructions: `You are a Critical Review Agent that evaluates the work done so far.
112
+ Your role is to:
113
+ 1. Review the research and analysis from previous agents
114
+ 2. Identify any gaps or areas that need more attention
115
+ 3. Suggest improvements or additional considerations
116
+
117
+ Start with "CRITICAL REVIEW:" and be constructive in your feedback.
118
+ Highlight both strengths and areas for improvement.`,
119
+ maxContextTokens: 8000,
120
+ },
121
+ {
122
+ agentId: 'summarizer',
123
+ provider: Providers.ANTHROPIC,
124
+ clientOptions: {
125
+ modelName: 'claude-haiku-4-5',
126
+ apiKey: process.env.ANTHROPIC_API_KEY,
127
+ },
128
+ instructions: `You are a Summary Agent that creates the final comprehensive output.
129
+ Your role is to:
130
+ 1. Synthesize all insights from the researcher, analyst, and reviewer
131
+ 2. Create a cohesive, actionable summary
132
+ 3. Provide clear recommendations or conclusions
133
+
134
+ Start with "EXECUTIVE SUMMARY:" followed by key sections.
135
+ End with "KEY RECOMMENDATIONS:" or "CONCLUSIONS:" as appropriate.`,
136
+ maxContextTokens: 8000,
137
+ },
138
+ ];
139
+
140
+ // Create sequential chain edges using our helper function
141
+ const agentIds = agents.map((a) => a.agentId);
142
+ const edges = createSequentialChainEdges(agentIds);
143
+
144
+ // Track agent progression
145
+ let currentAgent = '';
146
+
147
+ // Create custom handlers
148
+ const customHandlers = {
149
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
150
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
151
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
152
+ [GraphEvents.ON_RUN_STEP]: {
153
+ handle: (
154
+ event: GraphEvents.ON_RUN_STEP,
155
+ data: t.StreamEventData
156
+ ): void => {
157
+ const runStepData = data as any;
158
+ if (runStepData?.name) {
159
+ currentAgent = runStepData.name;
160
+ console.log(`\n→ ${currentAgent} is processing...`);
161
+ }
162
+ aggregateContent({ event, data: data as t.RunStep });
163
+ },
164
+ },
165
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
166
+ handle: (
167
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
168
+ data: t.StreamEventData
169
+ ): void => {
170
+ const runStepData = data as any;
171
+ if (runStepData?.name) {
172
+ console.log(`✓ ${runStepData.name} completed`);
173
+ }
174
+ aggregateContent({
175
+ event,
176
+ data: data as unknown as { result: t.ToolEndEvent },
177
+ });
178
+ },
179
+ },
180
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
181
+ handle: (
182
+ event: GraphEvents.ON_RUN_STEP_DELTA,
183
+ data: t.StreamEventData
184
+ ): void => {
185
+ aggregateContent({ event, data: data as t.RunStepDeltaEvent });
186
+ },
187
+ },
188
+ [GraphEvents.ON_MESSAGE_DELTA]: {
189
+ handle: (
190
+ event: GraphEvents.ON_MESSAGE_DELTA,
191
+ data: t.StreamEventData
192
+ ): void => {
193
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
194
+ },
195
+ },
196
+ };
197
+
198
+ // Create multi-agent run configuration
199
+ const runConfig: t.RunConfig = {
200
+ runId: `sequential-chain-${Date.now()}`,
201
+ graphConfig: {
202
+ type: 'multi-agent',
203
+ agents,
204
+ edges,
205
+ },
206
+ customHandlers,
207
+ returnContent: true,
208
+ };
209
+
210
+ try {
211
+ // Create and execute the run
212
+ const run = await Run.create(runConfig);
213
+
214
+ // Test with a complex question that benefits from multiple perspectives
215
+ const userMessage =
216
+ 'I want to launch a new mobile app for personal finance management. What should I consider?';
217
+ conversationHistory.push(new HumanMessage(userMessage));
218
+
219
+ console.log(`User: "${userMessage}"\n`);
220
+ console.log('Starting sequential agent chain...\n');
221
+
222
+ const config = {
223
+ configurable: {
224
+ thread_id: 'sequential-chain-1',
225
+ },
226
+ streamMode: 'values',
227
+ version: 'v2' as const,
228
+ };
229
+
230
+ // Process with streaming
231
+ const inputs = {
232
+ messages: conversationHistory,
233
+ };
234
+
235
+ const finalContentParts = await run.processStream(inputs, config);
236
+ const finalMessages = run.getRunMessages();
237
+
238
+ if (finalMessages) {
239
+ conversationHistory.push(...finalMessages);
240
+ }
241
+
242
+ console.log('\n\n=== Final Output ===');
243
+ console.log('Sequential chain completed successfully!');
244
+ console.log(`Total content parts: ${contentParts.length}`);
245
+
246
+ // Display the buffer accumulation
247
+ console.log('\n=== Agent Outputs (Buffer Accumulation) ===');
248
+
249
+ const aiMessages = conversationHistory.filter(
250
+ (msg) => msg._getType() === 'ai'
251
+ );
252
+
253
+ aiMessages.forEach((msg, index) => {
254
+ console.log(`\n--- Agent ${index + 1}: ${agentIds[index]} ---`);
255
+ console.log(msg.content);
256
+
257
+ // Show buffer preview for next agent (except last)
258
+ if (index < aiMessages.length - 1) {
259
+ const bufferSoFar = getBufferString(aiMessages.slice(0, index + 1));
260
+ console.log(
261
+ `\n[Buffer passed to ${agentIds[index + 1]}]: ${bufferSoFar.slice(0, 150)}...`
262
+ );
263
+ }
264
+ });
265
+
266
+ // Demonstrate that each agent built upon previous results
267
+ console.log('\n=== Chain Analysis ===');
268
+ console.log('1. Researcher provided initial findings');
269
+ console.log('2. Analyst built upon research with deeper insights');
270
+ console.log('3. Reviewer critiqued and identified gaps');
271
+ console.log('4. Summarizer synthesized everything into actionable output');
272
+ } catch (error) {
273
+ console.error('Error in sequential agent chain test:', error);
274
+ }
275
+ }
276
+
277
+ // Run the test
278
+ testSequentialAgentChain();
@@ -0,0 +1,220 @@
1
+ import { config } from 'dotenv';
2
+ config();
3
+
4
+ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
5
+ import { Run } from '@/run';
6
+ import { Providers, GraphEvents } from '@/common';
7
+ import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
8
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
9
+ import type * as t from '@/types';
10
+
11
+ const conversationHistory: BaseMessage[] = [];
12
+
13
+ /**
14
+ * Example of conditional multi-agent system
15
+ *
16
+ * Graph structure:
17
+ * START -> classifier
18
+ * classifier -> technical_expert (if technical question)
19
+ * classifier -> business_expert (if business question)
20
+ * classifier -> general_assistant (otherwise)
21
+ * [all experts] -> END
22
+ */
23
+ async function testConditionalMultiAgent() {
24
+ console.log('Testing Conditional Multi-Agent System...\n');
25
+
26
+ // Set up content aggregator
27
+ const { contentParts, aggregateContent } = createContentAggregator();
28
+
29
+ // Define specialized agents
30
+ const agents: t.AgentInputs[] = [
31
+ {
32
+ agentId: 'classifier',
33
+ provider: Providers.ANTHROPIC,
34
+ clientOptions: {
35
+ modelName: 'claude-haiku-4-5',
36
+ apiKey: process.env.ANTHROPIC_API_KEY,
37
+ },
38
+ instructions:
39
+ 'You are a query classifier. Analyze user questions and determine if they are technical, business-related, or general.',
40
+ maxContextTokens: 8000,
41
+ },
42
+ {
43
+ agentId: 'technical_expert',
44
+ provider: Providers.ANTHROPIC,
45
+ clientOptions: {
46
+ modelName: 'claude-haiku-4-5',
47
+ apiKey: process.env.ANTHROPIC_API_KEY,
48
+ },
49
+ instructions:
50
+ 'You are a technical expert. Provide detailed technical answers about programming, systems, and technology.',
51
+ maxContextTokens: 8000,
52
+ },
53
+ {
54
+ agentId: 'business_expert',
55
+ provider: Providers.ANTHROPIC,
56
+ clientOptions: {
57
+ modelName: 'claude-haiku-4-5',
58
+ apiKey: process.env.ANTHROPIC_API_KEY,
59
+ },
60
+ instructions:
61
+ 'You are a business expert. Provide insights on business strategy, operations, and management.',
62
+ maxContextTokens: 8000,
63
+ },
64
+ {
65
+ agentId: 'general_assistant',
66
+ provider: Providers.ANTHROPIC,
67
+ clientOptions: {
68
+ modelName: 'claude-haiku-4-5',
69
+ apiKey: process.env.ANTHROPIC_API_KEY,
70
+ },
71
+ instructions:
72
+ 'You are a helpful general assistant. Answer questions on a wide range of topics.',
73
+ maxContextTokens: 8000,
74
+ },
75
+ ];
76
+
77
+ // Define conditional edges
78
+ // These create handoff tools with conditional routing logic
79
+ const edges: t.GraphEdge[] = [
80
+ {
81
+ from: 'classifier',
82
+ to: ['technical_expert', 'business_expert', 'general_assistant'],
83
+ description: 'Route to appropriate expert based on query type',
84
+ condition: (state: t.BaseGraphState) => {
85
+ // Simple keyword-based routing for demo
86
+ // In a real system, this would use the classifier's analysis
87
+ const lastMessage = state.messages[state.messages.length - 1];
88
+ const content = lastMessage.content?.toString().toLowerCase() || '';
89
+
90
+ if (
91
+ content.includes('code') ||
92
+ content.includes('programming') ||
93
+ content.includes('technical')
94
+ ) {
95
+ return 'technical_expert';
96
+ } else if (
97
+ content.includes('business') ||
98
+ content.includes('strategy') ||
99
+ content.includes('market')
100
+ ) {
101
+ return 'business_expert';
102
+ } else {
103
+ return 'general_assistant';
104
+ }
105
+ },
106
+ },
107
+ ];
108
+
109
+ // Track selected expert
110
+ let selectedExpert = '';
111
+
112
+ // Create custom handlers
113
+ const customHandlers = {
114
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
115
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
116
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
117
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
118
+ handle: (
119
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
120
+ data: t.StreamEventData
121
+ ): void => {
122
+ aggregateContent({
123
+ event,
124
+ data: data as unknown as { result: t.ToolEndEvent },
125
+ });
126
+ },
127
+ },
128
+ [GraphEvents.ON_RUN_STEP]: {
129
+ handle: (
130
+ event: GraphEvents.ON_RUN_STEP,
131
+ data: t.StreamEventData
132
+ ): void => {
133
+ const runStepData = data as any;
134
+ if (runStepData?.name && runStepData.name !== 'classifier') {
135
+ selectedExpert = runStepData.name;
136
+ console.log(`Routing to: ${selectedExpert}`);
137
+ }
138
+ aggregateContent({ event, data: data as t.RunStep });
139
+ },
140
+ },
141
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
142
+ handle: (
143
+ event: GraphEvents.ON_RUN_STEP_DELTA,
144
+ data: t.StreamEventData
145
+ ): void => {
146
+ aggregateContent({ event, data: data as t.RunStepDeltaEvent });
147
+ },
148
+ },
149
+ [GraphEvents.ON_MESSAGE_DELTA]: {
150
+ handle: (
151
+ event: GraphEvents.ON_MESSAGE_DELTA,
152
+ data: t.StreamEventData
153
+ ): void => {
154
+ aggregateContent({ event, data: data as t.MessageDeltaEvent });
155
+ },
156
+ },
157
+ };
158
+
159
+ // Create multi-agent run configuration
160
+ const runConfig: t.RunConfig = {
161
+ runId: `conditional-multi-agent-${Date.now()}`,
162
+ graphConfig: {
163
+ type: 'multi-agent',
164
+ agents,
165
+ edges,
166
+ },
167
+ customHandlers,
168
+ returnContent: true,
169
+ };
170
+
171
+ try {
172
+ // Create and execute the run
173
+ const run = await Run.create(runConfig);
174
+
175
+ // Test with different types of questions
176
+ const testQuestions = [
177
+ 'How do I implement a binary search tree in Python?',
178
+ 'What are the key strategies for market expansion?',
179
+ 'What is the capital of France?',
180
+ ];
181
+
182
+ const config = {
183
+ configurable: {
184
+ thread_id: 'conditional-conversation-1',
185
+ },
186
+ streamMode: 'values',
187
+ version: 'v2' as const,
188
+ };
189
+
190
+ for (const question of testQuestions) {
191
+ console.log(`\n--- Processing: "${question}" ---\n`);
192
+
193
+ // Reset for each question
194
+ selectedExpert = '';
195
+ conversationHistory.length = 0;
196
+ conversationHistory.push(new HumanMessage(question));
197
+
198
+ // Process with streaming
199
+ const inputs = {
200
+ messages: conversationHistory,
201
+ };
202
+
203
+ const finalContentParts = await run.processStream(inputs, config);
204
+ const finalMessages = run.getRunMessages();
205
+
206
+ if (finalMessages) {
207
+ conversationHistory.push(...finalMessages);
208
+ }
209
+
210
+ console.log(`\n\nExpert used: ${selectedExpert}`);
211
+ console.log('Content parts:', contentParts.length);
212
+ console.log('---');
213
+ }
214
+ } catch (error) {
215
+ console.error('Error in conditional multi-agent test:', error);
216
+ }
217
+ }
218
+
219
+ // Run the test
220
+ testConditionalMultiAgent();