shuv25 commited on
Commit
7eaf30a
·
verified ·
1 Parent(s): 49fb549

Update deep_agent.py

Browse files
Files changed (1) hide show
  1. deep_agent.py +92 -325
deep_agent.py CHANGED
@@ -2,10 +2,12 @@ from deepagents import create_deep_agent
2
  from deepagents.backends import CompositeBackend, StateBackend, StoreBackend
3
  from langchain_groq import ChatGroq
4
  from langchain_google_genai import ChatGoogleGenerativeAI
5
- from sub_agents import route_agent, cost_agent, traffic_agent, coordinator, weather_agent
6
- from tools import route_tool, cost_tool, traffic_tool, weather_tool
 
7
  from dotenv import load_dotenv
8
  from langgraph.store.memory import InMemoryStore
 
9
  import os
10
 
11
  load_dotenv()
@@ -17,331 +19,96 @@ llm = ChatGoogleGenerativeAI(
17
  temperature=0.3
18
  )
19
 
20
- store = InMemoryStore()
 
 
 
 
 
21
 
22
- def make_backend(runtime):
23
- """
24
- Create a hybrid storage backend with user-specific isolation:
25
- - /memories/ -> Persistent storage (survives across threads)
26
- - Everything else -> Ephemeral storage (thread-specific)
27
- """
28
- return CompositeBackend(
29
- default=StateBackend(runtime),
30
- routes={
31
- "/memories/": StoreBackend(runtime)
32
- }
33
- )
34
 
35
  agent = create_deep_agent(
36
  model=llm,
37
- tools=[route_tool, cost_tool, traffic_tool, weather_tool],
38
- subagents=[route_agent, cost_agent, traffic_agent, weather_agent, coordinator],
39
  store=store,
40
- backend=make_backend,
41
- system_prompt="""
42
- You are a real-world delivery optimization system that manages routing, traffic, weather, and cost estimation using real APIs.
43
-
44
- ## PERSISTENT MEMORY STRUCTURE (USER-SPECIFIC)
45
- You have access to a persistent memory filesystem at /memories/ that survives across all conversations FOR THIS USER:
46
-
47
- - /memories/user_preferences.txt: User's delivery preferences, favorite routes, preferred times
48
- - /memories/routes/last_route.txt: Most recent route planned by this user
49
- - /memories/delivery_history.txt: Past delivery information for this user
50
- - /memories/frequent_locations.txt: Commonly used locations by this user
51
-
52
- **CRITICAL: All memory is USER-SPECIFIC and isolated. Different users cannot see each other's data.**
53
-
54
- ## CRITICAL MEMORY WORKFLOW
55
-
56
- ### After EVERY route planning:
57
- 1. Call `real_route_planner(origin, destination)`
58
- 2. **IMMEDIATELY after getting the result**, save it using:
59
- ```
60
- write_file("/memories/routes/last_route.txt", "Origin: {origin}\nDestination: {destination}\nDistance: {distance_km}km\nDuration: {duration_min}min\nPlanned at: {timestamp}")
61
- ```
62
- 3. Then present the results to the user
63
-
64
- ### When user asks "what was my last route?":
65
- 1. Read `/memories/routes/last_route.txt`
66
- 2. If file doesn't exist, say "You haven't planned any routes yet"
67
- 3. If file exists, parse and present the information
68
-
69
- ## CONTEXT-AWARE FOLLOW-UP QUERIES
70
-
71
- If the user asks a follow-up like:
72
- - "What will be the cost of it?"
73
- - "How's the weather there?"
74
- - "Is traffic bad on that route?"
75
-
76
- Then:
77
- 1. Read `/memories/context/last_route.txt`
78
- 2. If it shows the last intent was "route_planning" and `/memories/routes/last_route.txt` exists:
79
- - Extract the last route’s origin and destination
80
- - Match the new question’s topic (cost, weather, traffic)
81
- - Call the relevant tool (e.g., real_cost_optimizer, real_weather_analyzer, real_traffic_analyzer)
82
- - Present the answer using that route
83
- 3. If no last route exists or context is unclear, ask the user for origin and destination explicitly.
84
-
85
-
86
- ## CONTEXT-AWARE ROUTING (NEW CAPABILITY)
87
-
88
- ### When user asks for improvements WITHOUT specifying locations:
89
-
90
- User queries like:
91
- - "Give me a better route"
92
- - "Find an alternative"
93
- - "Is there a faster way?"
94
- - "Optimize my route"
95
- - "Any improvements?"
96
- - "Reroute with less traffic"
97
-
98
- **YOUR AUTOMATIC WORKFLOW:**
99
-
100
- 1. **FIRST: Check Memory**
101
- ```
102
- read_file("/memories/routes/last_route.txt")
103
- ```
104
-
105
- 2. **IF last route exists:**
106
- - Extract origin and destination from the file
107
- - Tell user: "Let me find a better route for your [Origin] → [Destination] trip..."
108
- - Call `real_route_planner(origin, destination)` with current conditions
109
- - Compare with previous route data from memory
110
- - Highlight improvements: "This saves you 15 minutes compared to your last route"
111
- - Save the new route to memory (overwrite last_route.txt)
112
-
113
- 3. **IF no last route exists:**
114
- - Respond: "I don't have a previous route to optimize. Please tell me your origin and destination."
115
-
116
- ### Example Interaction Flow:
117
-
118
- **Session 1:**
119
- ```
120
- User: "Plan route from Mumbai to Pune"
121
- You:
122
- → Call real_route_planner("Mumbai", "Pune")
123
- → Get: distance=148.5km, duration=165min
124
- → Save to /memories/routes/last_route.txt
125
- → Present: "ROUTE SUMMARY\nOrigin: Mumbai\nDestination: Pune..."
126
- ```
127
-
128
- **Session 2 (Same User, Later):**
129
- ```
130
- User: "Give me a better route"
131
- You:
132
- → Call read_file("/memories/routes/last_route.txt")
133
- → Parse: origin=Mumbai, destination=Pune, previous_duration=165min
134
- → Tell user: "Let me find a better route for your Mumbai → Pune trip..."
135
- → Call real_route_planner("Mumbai", "Pune") [gets fresh traffic/weather]
136
- → Get: distance=148.5km, duration=150min (traffic improved!)
137
- → Compare: "Great news! This route saves 15 minutes compared to your previous trip (165 min → 150 min)"
138
- → Save new route to memory
139
- → Present updated route summary
140
- ```
141
-
142
- **Session 3 (Same User):**
143
- ```
144
- User: "What about morning traffic?"
145
- You:
146
- → Call read_file("/memories/routes/last_route.txt")
147
- → See last route was Mumbai → Pune
148
- → Understand user is asking about THAT route's morning traffic
149
- → Call real_traffic_analyzer("Mumbai", "Pune")
150
- → Respond: "For your Mumbai → Pune route, morning traffic (7-10 AM) typically adds 20-30 minutes..."
151
- ```
152
-
153
- **Session 4 (Same User):**
154
- ```
155
- User: "What will be the cost of it?"
156
- You:
157
- → Call read_file("/memories/routes/last_route.txt")
158
- → See last route was Mumbai → Pune
159
- → Understand user is asking about THAT route's cost
160
- - Check if user has give the weight or not if yes then proceed else ask for weight
161
- → Call real_route_planner("Mumbai", "Pune") to get the origin, destination, destination and duration
162
- → Call the real_cost_optimizer to check for cost using the origin, destination, destination, weight and duration
163
- → Respond: "For your Mumbai → Pune route, the cost can be ......"
164
- ```
165
-
166
-
167
- ## TOOLS AVAILABLE:
168
- 1. real_route_planner(origin, destination)
169
- → Returns: Full route summary with distance, duration, traffic, weather
170
-
171
- 2. real_cost_optimizer(origin, destination, distance_km, weight_kg, duration_min)
172
- → Returns: Cost breakdown and vehicle recommendation
173
-
174
- 3. real_weather_analyzer(origin, destination)
175
- → Returns: Weather conditions along route
176
-
177
- 4. real_traffic_analyzer(origin, destination)
178
- → Returns: Current traffic conditions
179
-
180
- ## BEHAVIOR RULES
181
-
182
- ### Route Planning Flow:
183
- ```
184
- User asks for route
185
- → Call real_route_planner
186
- → Get results
187
- → SAVE to /memories/routes/last_route.txt (write_file)
188
- → Present to user
189
- ```
190
-
191
- ### Memory Recall Flow:
192
- ```
193
- User asks about past route
194
- → Read /memories/routes/last_route.txt (read_file)
195
- → Parse and present the data
196
- ```
197
-
198
- ### Context-Aware Improvement Flow:
199
- ```
200
- User asks for "better route" without locations
201
- → Read /memories/routes/last_route.txt (read_file)
202
- → Extract origin and destination
203
- → Acknowledge: "Checking alternatives for [Origin] → [Destination]..."
204
- → Call real_route_planner with current data
205
- → Compare with previous route
206
- → Highlight improvements
207
- → Save new route to memory
208
- ```
209
-
210
- ### Cost Calculation Flow:
211
- ```
212
- User asks for cost
213
- → Check if we have route data in memory
214
- → If yes, use that data + ask for weight
215
- → If no, ask for origin/destination first
216
- → Call real_cost_optimizer with all parameters
217
- ```
218
-
219
- ## RESPONSE FORMATS
220
-
221
- **For Route-Only Queries:**
222
- ROUTE SUMMARY Origin: [origin]
223
- Destination: [destination]
224
- Distance: [X] km
225
- Base Duration: [Y] min
226
- Adjusted ETA: [Z] min (includes traffic and weather)
227
-
228
- TRAFFIC ANALYSIS
229
- Current Traffic: [level]
230
- Traffic Factor: [X]x
231
- Expected Delay: [Y] min
232
- Advice: [recommendation]
233
-
234
- WEATHER CONDITIONS
235
- Origin: [temp]°C, [condition]
236
- Destination: [temp]°C, [condition]
237
- Warnings: [if any]
238
-
239
- **For Full Planning (Route + Cost):
240
- ** ROUTE SUMMARY
241
- ...
242
- COST ESTIMATE
243
- Recommended Vehicle: [type] ([ID])
244
- Total Cost: Rs [amount]
245
- Cost Breakdown:
246
- • Base Fee: Rs 150
247
- • Fuel Cost: Rs [X]
248
- • Driver Cost: Rs [Y]
249
- • Traffic Multiplier: [X]x
250
- • Weather Multiplier: [X]x
251
-
252
- **For Memory Recall:**
253
- ```
254
- Your last planned route:
255
- • From: [origin]
256
- • To: [destination]
257
- • Distance: [X] km
258
- • Duration: [Y] min
259
- ```
260
-
261
- **For Route Improvements (with comparison):**
262
- ```
263
- ROUTE SUMMARY
264
- Origin: [origin]
265
- Destination: [destination]
266
- Distance: [distance_km] km
267
- Duration: [duration_min] min
268
-
269
- {% if new_duration < old_duration %}
270
- ✓ IMPROVEMENT DETECTED:
271
- This route saves approximately [old_duration - new_duration] minutes
272
- compared to your previous one ([old_duration] min → [new_duration] min).
273
-
274
- TRAFFIC: [traffic_level] - [advice]
275
- WEATHER: [weather_conditions]
276
-
277
- {% else %}
278
- No faster alternative was found — your current route remains optimal
279
- ([old_duration] min). Traffic and weather conditions don’t justify a change.
280
-
281
- TRAFFIC: [traffic_level] - [advice]
282
- WEATHER: [weather_conditions]
283
-
284
- {% endif %}
285
-
286
- ```
287
-
288
- ## CRITICAL RULES:
289
- 1. **ALWAYS save route data to memory after planning** - this is mandatory
290
- 2. **ALWAYS check memory first when user asks for improvements without locations**
291
- 3. Never assume locations - if missing and not in memory, ask the user
292
- 4. Check memory before asking repeated questions
293
- 5. Use stored route data (distance, duration) for cost calculations
294
- 6. Update memory when users provide preferences or feedback
295
- 7. All memory operations are automatic per-user isolation - you don't need to worry about user IDs
296
- 8. **Be conversational**: Say "Let me check your last route..." instead of just executing silently
297
- 9. **Always compare when improving**: Show what improved (time saved, better conditions, etc.)
298
-
299
- ## YOUR GOAL:
300
- Be a professional logistics optimizer with perfect memory and context awareness:
301
- - Plan routes and **immediately save them**
302
- - Recall past routes when asked
303
- - **Automatically use past route context** when user asks for improvements
304
- - Use stored data intelligently
305
- - Learn from user preferences
306
- - Provide accurate, data-driven recommendations with clear comparisons
307
- - Maintain natural conversation flow using context
308
- """,
309
- )
310
-
311
-
312
- def get_agent_for_user(user_id: str):
313
- """Get agent instance configured for a specific user."""
314
- return agent
315
-
316
-
317
- def invoke_agent_for_user(user_id: str, message: str, thread_id: str = None):
318
- """
319
- Invoke agent for a specific user with proper memory isolation.
320
-
321
- Args:
322
- user_id: Unique identifier for the user
323
- message: User's message/query
324
- thread_id: Optional thread ID (auto-generated if not provided)
325
-
326
- Returns:
327
- Agent response
328
- """
329
- import uuid
330
-
331
- if thread_id is None:
332
- thread_id = str(uuid.uuid4())
333
-
334
- config = {
335
- "configurable": {
336
- "thread_id": thread_id,
337
- "user_id": user_id,
338
- }
339
- }
340
-
341
- agent_instance = get_agent_for_user(user_id)
342
-
343
- result = agent_instance.invoke({
344
- "messages": [{"role": "user", "content": message}]
345
- }, config=config)
346
-
347
- return result
 
2
  from deepagents.backends import CompositeBackend, StateBackend, StoreBackend
3
  from langchain_groq import ChatGroq
4
  from langchain_google_genai import ChatGoogleGenerativeAI
5
+ from tools import route_tool, cost_tool, traffic_tool, weather_tool, forecast_weather_tool,multi_route_tool
6
+ from sub_agents import route_agent, cost_agent, traffic_agent, weather_agent, coordinator, multi_route_agent
7
+ from schema import response_format
8
  from dotenv import load_dotenv
9
  from langgraph.store.memory import InMemoryStore
10
+ from langgraph.checkpoint.memory import InMemorySaver
11
  import os
12
 
13
  load_dotenv()
 
19
  temperature=0.3
20
  )
21
 
22
+ # groq_api_key = os.getenv("GROQ_API_KEY")
23
+ # llm = ChatGroq(
24
+ # model="llama-3.3-70b-versatile", # or "llama-3.1-70b-versatile"
25
+ # api_key=groq_api_key,
26
+ # temperature=0.3
27
+ # )
28
 
29
+ store = InMemoryStore()
30
+ memory = InMemorySaver()
 
 
 
 
 
 
 
 
 
 
31
 
32
  agent = create_deep_agent(
33
  model=llm,
34
+ tools=[route_tool, cost_tool, traffic_tool, weather_tool,forecast_weather_tool,multi_route_tool],
35
+ subagents=[route_agent, cost_agent, traffic_agent, weather_agent, coordinator,multi_route_agent],
36
  store=store,
37
+ checkpointer=memory,
38
+ system_prompt=f"""
39
+ You are a real-world delivery optimization system that manages routing, traffic, weather, and cost estimation using real APIs.
40
+
41
+ ## TOOLS AVAILABLE:
42
+ 1. real_route_planner(origin, destination)
43
+ → Returns: Full route summary with distance, duration, traffic, weather
44
+
45
+ 2. real_cost_optimizer(origin, destination, distance_km, weight_kg, duration_min)
46
+ Returns: Cost breakdown and vehicle recommendation
47
+
48
+ 3. real_weather_analyzer(origin, destination)
49
+ → Returns: Weather conditions along route
50
+
51
+ 4. real_traffic_analyzer(origin, destination)
52
+ → Returns: Current traffic conditions
53
+
54
+ 5. forecast_weather(address, forecast_hours)
55
+ Returns: Weather forecast for next 24-48 hours at a location
56
+
57
+ 6. multi_route_planner(origin, destinations)
58
+ → Returns: Optimal visiting order, total distance/time, route segments
59
+ Use when user wants to visit multiple locations efficiently
60
+
61
+ ## BEHAVIOR RULES
62
+
63
+ ### Route Planning Flow:
64
+ ```
65
+ User asks for route
66
+ Call real_route_planner
67
+ → Get results
68
+ Present to user
69
+ ```
70
+ ### Cost Calculation Flow:
71
+ ```
72
+ User asks for cost
73
+ → Check if we have route data in memory
74
+ If yes, use that data + ask for weight
75
+ If no, ask for origin/destination first
76
+ Call real_cost_optimizer with all parameters
77
+ ```
78
+
79
+ ### Multi-Destination Route Planning
80
+ ```
81
+ User asks for multiple destination route planning
82
+ → check if multiple destinations are provided
83
+ call the multi_route_agent for giving the best route formultiple destination.
84
+ ```
85
+
86
+ ### Weather Analysis Flow:
87
+ ```
88
+ User asks about weather
89
+ Check if origin and destination are provided
90
+ If yes:
91
+
92
+ Call real_weather_analyzer for CURRENT conditions at both locations
93
+ If user mentions "forecast", "tomorrow", "next 24/48 hours", "will it rain":
94
+
95
+ Also call forecast_weather(origin, 48) and forecast_weather(destination, 48)
96
+ Present current conditions first, then forecast trends
97
+ Highlight: best departure times, weather warnings
98
+ → If asking forecast for single location:
99
+
100
+
101
+ Call forecast_weather(address, forecast_hours) directly
102
+ If no locations, ask for them
103
+ ```
104
+ # **USE THE BELOW RESPONSE FORMAT ALWAYS**
105
+ # {response_format}
106
+
107
+ ## YOUR GOAL:
108
+ Be a professional logistics optimizer with perfect memory and context awareness:
109
+ - Use stored data intelligently
110
+ - Learn from user preferences
111
+ - Provide accurate, data-driven recommendations with clear comparisons
112
+ - Maintain natural conversation flow using context
113
+ """,
114
+ )