-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13-SupervisorGraph.py
More file actions
338 lines (257 loc) · 11.2 KB
/
13-SupervisorGraph.py
File metadata and controls
338 lines (257 loc) · 11.2 KB
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
330
331
332
333
334
335
336
337
338
# 14-SupervisorGraph.py
# We will create a graph with a supervisor node which will direct the user to the required node
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
from langgraph.graph.message import add_messages, AnyMessage
from typing import TypedDict, Annotated, List, Literal, Any
from langgraph.checkpoint.memory import MemorySaver
from config.secret_keys import OPENAI_API_KEY
from config.config import get_llm
from utils.graph_img_generation import save_and_show_graph
# define LLM
llm = get_llm()
# define Custom State
class CustomState(TypedDict):
messages: Annotated[List[AnyMessage], add_messages]
next_node: str
# define Model for structured output
class SupervisorModel(BaseModel):
next_node: Literal['ASSISTANT', 'MATH_EXPERT', 'SCIENCE_EXPERT', 'HISTORY_EXPERT'] = Field(
...,
description="The next node to which the user should be directed. It can be 'ASSISTANT', 'MATH_EXPERT', 'SCIENCE_EXPERT', or 'HISTORY_EXPERT'.",
)
# define math tools
def multiply(a: int, b: int) -> int:
"""Multiply a and b.
Args:
a: first int
b: second int
"""
return a * b
def add(a: int, b: int) -> int:
"""Add a and b.
Args:
a: first int
b: second int
"""
return a + b
def subtract(a: int, b: int) -> int:
"""Subtract a and b.
Args:
a: first int
b: second int
"""
return a - b
def divide(a: int, b: int) -> float: # Fixed: should return float
"""Divide a and b.
Args:
a: first int
b: second int
"""
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
tools = [add, subtract, multiply, divide]
# define NODES
# SUPERVISOR NODE
def supervisor(state):
"""
Supervisor node that directs the user to Math Expert, Science Expert, or History Expert.
"""
print("----------INSIDE SUPERVISOR----------")
supervisor_prompt = """
You are an intelligent routing supervisor responsible for directing users to the most appropriate expert based on their question.
Analyze the user's message and determine which expert can best help them:
- MATH_EXPERT: Choose for mathematical calculations, equations, algebra, geometry, statistics, calculus, or any numerical problem-solving
- SCIENCE_EXPERT: Choose for physics, chemistry, biology, earth sciences, astronomy, or scientific concepts and explanations
- HISTORY_EXPERT: Choose for historical events, dates, civilizations, wars, historical figures, or cultural history
- ASSISTANT: Choose for general questions, greetings, or topics that don't clearly fit the other categories
Consider the primary focus of the question. If a question touches multiple areas, route to the most relevant expert.
"""
messages = [SystemMessage(content=supervisor_prompt)] + state["messages"]
llm_with_structured_output = llm.with_structured_output(SupervisorModel)
response = llm_with_structured_output.invoke(messages)
print("Supervisor response:", response)
return {
**state,
"next_node": response.next_node,
}
def supervisor_router(state):
print("----------INSIDE SUPERVISOR ROUTER----------")
next_node = state["next_node"]
valid_nodes = ["ASSISTANT", "MATH_EXPERT", "SCIENCE_EXPERT", "HISTORY_EXPERT"]
if next_node not in valid_nodes:
# default to the assistant if the next node is not valid
print(f"Invalid next node '{next_node}'. Defaulting to 'ASSISTANT'.")
next_node = "ASSISTANT"
return next_node
# ASSISTANT NODE
def assistant(state):
"""
Assistant node that provides general assistance.
"""
print("----------INSIDE ASSISTANT----------")
assistant_prompt = """
You are a helpful general assistant. You provide clear, informative responses to a wide range of questions.
Your role is to:
- Answer general knowledge questions
- Provide helpful explanations on various topics
- Assist with everyday questions and tasks
- Offer guidance when users need general help
You can help with:
- General knowledge inquiries
- Math problems (basic)
- Science questions (basic)
- History questions (basic)
Be friendly, concise, and helpful. If a question requires specialized expertise in math, science, or history,
let the user know they might want to ask about that specific topic to get more detailed help.
Your response should be short and friendly, encouraging users to ask more questions if they need further assistance.
"""
messages = [SystemMessage(content=assistant_prompt)] + state["messages"]
response = llm.invoke(messages)
return {
"messages": response
}
# MATH EXPERT NODE
def math_expert(state):
"""
Math expert node that provides answers to math-related questions.
"""
print("----------INSIDE MATH EXPERT----------")
math_prompt = """
You are a specialized mathematics expert with access to calculation tools. You excel at solving mathematical problems and explaining mathematical concepts.
Your capabilities include:
- Solving arithmetic problems (addition, subtraction, multiplication, division)
- Explaining mathematical concepts and procedures
- Working through step-by-step solutions
- Helping with algebra, geometry, statistics, and other math topics
Available tools:
- add(a, b): Add two numbers
- subtract(a, b): Subtract two numbers
- multiply(a, b): Multiply two numbers
- divide(a, b): Divide two numbers
When solving problems:
1. Break down complex problems into steps
2. Use the available tools for calculations when needed
3. Show your work and explain your reasoning
4. Provide clear, accurate answers with explanations
Always use the tools for calculations to ensure accuracy, even for simple operations.
Your response should be short, clear, and educational, encouraging users to ask follow-up questions if they need further assistance.
"""
messages = [SystemMessage(content=math_prompt)] + state["messages"]
llm_with_tools = llm.bind_tools(tools)
response = llm_with_tools.invoke(messages)
return {
"messages": response
}
# SCIENCE EXPERT NODE
def science_expert(state):
"""
Science expert node that provides answers to science-related questions.
"""
print("----------INSIDE SCIENCE EXPERT----------")
science_prompt = """
You are a knowledgeable science expert specializing in multiple scientific disciplines including physics, chemistry, biology, earth sciences, and astronomy.
Your expertise covers:
- Physics: mechanics, thermodynamics, electromagnetism, quantum physics, relativity
- Chemistry: atomic structure, chemical reactions, organic/inorganic chemistry, biochemistry
- Biology: cell biology, genetics, evolution, ecology, human anatomy and physiology
- Earth Sciences: geology, meteorology, oceanography, environmental science
- Astronomy: solar system, stars, galaxies, cosmology
When answering questions:
- Provide scientifically accurate information
- Explain complex concepts in an understandable way
- Use examples and analogies when helpful
- Cite scientific principles and laws when relevant
- Encourage scientific thinking and curiosity
Make your explanations clear and educational, adapting to the user's apparent level of scientific background.
Your response should be short, clear, and educational, encouraging users to ask follow-up questions if they need further assistance.
"""
messages = [SystemMessage(content=science_prompt)] + state["messages"]
response = llm.invoke(messages)
return {
"messages": response
}
# HISTORY EXPERT NODE
def history_expert(state):
"""
History expert node that provides answers to history-related questions.
"""
print("----------INSIDE HISTORY EXPERT----------")
history_prompt = """
You are a comprehensive history expert with deep knowledge spanning all periods of human history and various civilizations.
Your expertise includes:
- Ancient civilizations (Egypt, Greece, Rome, Mesopotamia, etc.)
- Medieval history and the Middle Ages
- Renaissance and Early Modern periods
- Modern history (18th-20th centuries)
- World wars and major conflicts
- Political, social, and cultural history
- Historical figures and their contributions
- Historical events and their significance
When answering historical questions:
- Provide accurate dates, names, and events
- Explain the context and significance of historical events
- Draw connections between past and present when relevant
- Present multiple perspectives when appropriate
- Use engaging storytelling while maintaining historical accuracy
- Cite important sources or acknowledge when information is debated among historians
Make history come alive by explaining not just what happened, but why it matters and how it shaped the world.
Your response should be short, clear, and educational, encouraging users to ask follow-up questions if they need further assistance.
"""
messages = [SystemMessage(content=history_prompt)] + state["messages"]
response = llm.invoke(messages)
return {
"messages": response
}
# Build the graph
builder = StateGraph(CustomState)
builder.add_node("supervisor", supervisor)
builder.add_node("assistant", assistant)
builder.add_node("math_expert", math_expert)
builder.add_node("math_expert_tools", ToolNode(tools))
builder.add_node("science_expert", science_expert)
builder.add_node("history_expert", history_expert)
builder.add_edge(START, "supervisor")
builder.add_conditional_edges(
"supervisor",
supervisor_router,
{
'ASSISTANT': "assistant",
'MATH_EXPERT': "math_expert",
'SCIENCE_EXPERT': "science_expert",
'HISTORY_EXPERT': "history_expert"
}
)
builder.add_conditional_edges(
"math_expert",
tools_condition, {
"tools": "math_expert_tools", # Map "tools" to your tool node name
"__end__": END # Map "__end__" to END
}
)
builder.add_edge("math_expert_tools", "math_expert")
builder.add_edge("assistant", END)
builder.add_edge("math_expert", END)
builder.add_edge("science_expert", END)
builder.add_edge("history_expert", END)
supervisor_graph = builder.compile(checkpointer=MemorySaver())
# save and show the graph image
save_and_show_graph(supervisor_graph, filename="13-SupervisorGraph", show_image=False)
if __name__ == "__main__":
# Specify a thread AKA session
config = {"configurable": {"thread_id": "1"}}
print("Welcome to the Supervisor Graph! Type 'exit' to quit.")
while True:
# Get user input
user_input = input("User: ")
if user_input.lower() == 'exit':
break
message = HumanMessage(content=user_input)
messages = supervisor_graph.invoke({"messages": [message]}, config) # Fixed: wrap in list
for m in messages['messages']:
m.pretty_print()
print("\n\n")