-
Notifications
You must be signed in to change notification settings - Fork 10
/
multi-agent.ts
329 lines (288 loc) · 8.85 KB
/
multi-agent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
import { BaseMessage } from "@langchain/core/messages";
import { HumanMessage } from "@langchain/core/messages";
import {
ChatPromptTemplate,
MessagesPlaceholder,
} from "@langchain/core/prompts";
import { Runnable } from "@langchain/core/runnables";
import { RunnableConfig } from "@langchain/core/runnables";
import { DynamicStructuredTool } from "@langchain/core/tools";
import { END, StateGraphArgs } from "@langchain/langgraph";
import { START, StateGraph } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { createCanvas } from "canvas";
import "dotenv/config";
import { writeFileSync } from "fs";
import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { JsonOutputToolsParser } from "langchain/output_parsers";
import { z } from "zod";
import { LiteralClient } from "@literalai/client";
const literalClient = new LiteralClient();
const cb = literalClient.instrumentation.langchain.literalCallback({
threadId: "Jokes",
chainTypesToIgnore: ["ChatPromptTemplate"],
});
interface AgentStateChannels {
messages: BaseMessage[];
// The agent node that last performed work
next: string;
}
// This defines the object that is passed between each node
// in the graph. We will create different nodes for each agent and tool
const agentStateChannels: StateGraphArgs<AgentStateChannels>["channels"] = {
messages: {
value: (x?: BaseMessage[], y?: BaseMessage[]) => (x ?? []).concat(y ?? []),
default: () => [],
},
next: {
value: (x?: string, y?: string) => y ?? x ?? END,
default: () => END,
},
};
const chartTool = new DynamicStructuredTool({
name: "generate_bar_chart",
description:
"Generates a bar chart from an array of data points using D3.js and displays it for the user.",
schema: z.object({
data: z
.object({
label: z.string(),
value: z.number(),
})
.array(),
}),
func: async ({ data }) => {
const d3 = await import("d3");
console.log("test test test");
const width = 500;
const height = 500;
const margin = { top: 20, right: 30, bottom: 30, left: 40 };
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
const x = d3
.scaleBand()
.domain(data.map((d) => d.label))
.range([margin.left, width - margin.right])
.padding(0.1);
const y = d3
.scaleLinear()
.domain([0, d3.max(data, (d) => d.value) ?? 0])
.nice()
.range([height - margin.bottom, margin.top]);
const colorPalette = [
"#e6194B",
"#3cb44b",
"#ffe119",
"#4363d8",
"#f58231",
"#911eb4",
"#42d4f4",
"#f032e6",
"#bfef45",
"#fabebe",
];
data.forEach((d, idx) => {
ctx.fillStyle = colorPalette[idx % colorPalette.length];
ctx.fillRect(
x(d.label) ?? 0,
y(d.value),
x.bandwidth(),
height - margin.bottom - y(d.value)
);
});
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.moveTo(margin.left, height - margin.bottom);
ctx.lineTo(width - margin.right, height - margin.bottom);
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "top";
x.domain().forEach((d) => {
const xCoord = (x(d) ?? 0) + x.bandwidth() / 2;
ctx.fillText(d, xCoord, height - margin.bottom + 6);
});
ctx.beginPath();
ctx.moveTo(margin.left, height - margin.top);
ctx.lineTo(margin.left, height - margin.bottom);
ctx.stroke();
ctx.textAlign = "right";
ctx.textBaseline = "middle";
const ticks = y.ticks();
ticks.forEach((d) => {
const yCoord = y(d); // height - margin.bottom - y(d);
ctx.moveTo(margin.left, yCoord);
ctx.lineTo(margin.left - 6, yCoord);
ctx.stroke();
ctx.fillText(d.toString(), margin.left - 8, yCoord);
});
console.log(canvas.toBuffer());
writeFileSync("chart.png", canvas.toBuffer());
return "Chart has been generated and displayed to the user!";
},
});
const tavilyTool = new TavilySearchResults();
async function createAgent(
llm: ChatOpenAI,
tools: any[],
systemPrompt: string
): Promise<Runnable> {
// Each worker node will be given a name and some tools.
const prompt = await ChatPromptTemplate.fromMessages([
["system", systemPrompt],
new MessagesPlaceholder("messages"),
new MessagesPlaceholder("agent_scratchpad"),
]);
const agent = await createOpenAIToolsAgent({
llm: llm as any,
tools,
prompt: prompt as any,
});
return new AgentExecutor({ agent, tools }) as any;
}
const members = ["researcher", "chart_generator"];
const systemPrompt =
"You are a supervisor tasked with managing a conversation between the" +
" following workers: {members}. Given the following user request," +
" respond with the worker to act next. Each worker will perform a" +
" task and respond with their results and status. When finished," +
" respond with FINISH.";
const options = [END, ...members];
// Define the routing function
const functionDef = {
name: "route",
description: "Select the next role.",
parameters: {
title: "routeSchema",
type: "object",
properties: {
next: {
title: "Next",
anyOf: [{ enum: options }],
},
},
required: ["next"],
},
};
const toolDef = {
type: "function",
function: functionDef,
} as const;
const prompt = ChatPromptTemplate.fromMessages([
["system", systemPrompt],
new MessagesPlaceholder("messages"),
[
"system",
"Given the conversation above, who should act next?" +
" Or should we FINISH? Select one of: {options}",
],
]);
async function main() {
const formattedPrompt = await prompt.partial({
options: options.join(", "),
members: members.join(", "),
});
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0,
});
const supervisorChain = formattedPrompt
.pipe(
llm.bindTools([toolDef], {
tool_choice: { type: "function", function: { name: "route" } },
})
)
.pipe(new JsonOutputToolsParser() as any)
// select the first one
.pipe((x) => (x as Array<any>)[0].args);
// Recall llm was defined as ChatOpenAI above
// It could be any other language model
const researcherAgent = await createAgent(
llm,
[tavilyTool],
"You are a web researcher. You may use the Tavily search engine to search the web for" +
" important information, so the Chart Generator in your team can make useful plots."
);
const researcherNode = async (
state: AgentStateChannels,
config?: RunnableConfig
) => {
const result = await researcherAgent.invoke(state, {
...config,
callbacks: [cb],
runName: "Researcher",
configurable: { thread_id: "42" },
});
return {
messages: [
new HumanMessage({ content: result.output, name: "Researcher" }),
],
};
};
const chartGenAgent = await createAgent(
llm,
[chartTool],
"You excel at generating bar charts. Use the researcher's information to generate the charts."
);
const chartGenNode = async (
state: AgentStateChannels,
config?: RunnableConfig
) => {
const result = await chartGenAgent.invoke(state, {
...config,
callbacks: [cb],
runName: "Chart Generator",
configurable: { thread_id: "42" },
});
return {
messages: [
new HumanMessage({ content: result.output, name: "ChartGenerator" }),
],
};
};
// 1. Create the graph
const workflow = new StateGraph<AgentStateChannels, unknown, string>({
channels: agentStateChannels as any,
}) // 2. Add the nodes; these will do the work
.addNode("researcher", researcherNode as any)
.addNode("chart_generator", chartGenNode as any)
.addNode("supervisor", supervisorChain);
// 3. Define the edges. We will define both regular and conditional ones
// After a worker completes, report to supervisor
members.forEach((member) => {
workflow.addEdge(member as any, "supervisor");
});
workflow.addConditionalEdges(
"supervisor",
((x: AgentStateChannels) => x.next) as any
);
workflow.addEdge(START, "supervisor");
const graph = workflow.compile();
const visu = await graph.getGraph().drawMermaidPng();
const arrayBuffer = await visu.arrayBuffer();
writeFileSync("graph.png", Buffer.from(arrayBuffer));
// literalClient.run({ name: 'Multi-agent' }).wrap(async () => {
const streamResults = graph.stream(
{
messages: [
new HumanMessage({
content: "What were the 3 most popular tv shows in 2023?",
}),
],
},
{
recursionLimit: 100,
configurable: { thread_id: "42" },
runName: "supervisor",
callbacks: [cb],
}
);
for await (const output of await streamResults) {
if (!output?.__end__) {
console.log(output);
console.log("----");
}
}
// });
}
main();