-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinventory_agent.py
More file actions
355 lines (295 loc) · 14.5 KB
/
inventory_agent.py
File metadata and controls
355 lines (295 loc) · 14.5 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
Smart Inventory Watchdog Agent
An intelligent monitoring system that acts as a 24/7 inventory guardian,
automatically tracking stock levels and triggering proactive reorder processes.
"""
import os
import json
from typing import List, Dict, Any, Optional
from datetime import datetime
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from ormcp_tools import (
ORMCPClient,
QueryTool,
GetAggregateTool,
UpdateTool,
InsertTool,
GetObjectModelSummaryTool
)
from notification_tool import EmailNotificationTool, create_inventory_alert_email, create_reorder_suggestion_email
class InventoryWatchdogAgent:
"""Smart Inventory Watchdog Agent for monitoring and managing inventory"""
def __init__(self,
openai_api_key: str,
ormcp_server_url: str = "http://localhost:8080",
model_name: str = "gpt-3.5-turbo",
temperature: float = 0.3,
admin_emails: Optional[List[str]] = None,
default_threshold: int = 50):
"""
Initialize the Inventory Watchdog Agent
Args:
openai_api_key: OpenAI API key
ormcp_server_url: URL of the ORMCP server
model_name: OpenAI model to use
temperature: Model temperature
admin_emails: List of admin email addresses for notifications
default_threshold: Default stock threshold for alerts
"""
self.openai_api_key = openai_api_key
self.ormcp_server_url = ormcp_server_url
self.model_name = model_name
self.temperature = temperature
self.admin_emails = admin_emails or []
self.default_threshold = default_threshold
# Initialize ORMCP client
self.ormcp_client = ORMCPClient(base_url=ormcp_server_url)
# Initialize LLM
self.llm = ChatOpenAI(
model=model_name,
temperature=temperature,
openai_api_key=openai_api_key
)
# Initialize tools
self.tools = []
self._setup_tools()
# Initialize agent
self.agent_executor = None
self._setup_agent()
def _setup_tools(self):
"""Set up all available tools"""
# ORMCP tools
self.tools.extend([
QueryTool(self.ormcp_client),
GetAggregateTool(self.ormcp_client),
UpdateTool(self.ormcp_client),
InsertTool(self.ormcp_client),
GetObjectModelSummaryTool(self.ormcp_client),
])
# Notification tool
email_tool = EmailNotificationTool()
self.tools.append(email_tool)
def _setup_agent(self):
"""Set up the LangChain agent"""
# Create agent using LangGraph (ReAct agent)
# The agent will use the tools and LLM to perform inventory monitoring tasks
self.agent_graph = create_react_agent(self.llm, self.tools)
# System context for the agent (will be included in messages)
self.system_context = """You are a Smart Inventory Watchdog Agent, an intelligent monitoring system
that acts as a 24/7 inventory guardian. Your responsibilities include:
1. **Real-Time Stock Monitoring**: Continuously monitor product inventory via ORMCP queries,
tracking items where stockQuantity < threshold
2. **Intelligent Alerting**: Automatically send email notifications to admins/suppliers when
stock falls below configurable thresholds
3. **Predictive Reordering**: Analyze historical sales trends to suggest optimal reorder
quantities using AI-powered forecasting
4. **Multi-Channel Notifications**: Support Gmail API, SMTP, and custom messaging integrations
5. **Threshold Management**: Configure per-product or per-category thresholds with dynamic
adjustment based on sales velocity
**Available Tools:**
- `query_products`: Query products with filters (e.g., find low-stock items)
- `get_aggregate`: Calculate aggregates (COUNT, SUM, AVG, MIN, MAX) for sales analysis
- `update_products`: Update product information (stock levels, reorder flags)
- `insert_objects`: Create reorder requests and inventory alerts
- `send_email_notification`: Send email alerts to stakeholders
- `get_object_model_summary`: Discover database schema and available classes
**Key Classes:**
- `com.acme.ecommerce.model.Product`: Product catalog with stockQuantity, price, category, etc.
- `com.acme.ecommerce.model.CustomerOrder`: Order information
- `com.acme.ecommerce.model.OrderItem`: Order line items for sales analysis
**Workflow:**
1. Query products where stockQuantity < threshold
2. Analyze sales trends using getAggregate on OrderItem
3. Calculate suggested reorder quantities based on sales velocity
4. Update products with reorder flags
5. Create reorder requests
6. Send email notifications to admins/suppliers
**IMPORTANT - Update Product Instructions:**
When updating a product (e.g., changing stockQuantity):
1. FIRST: Query the product using query_products with filter "id = [product_id]" to get its complete current data
2. THEN: Use update_products with the complete product object including the ID and the field(s) to update
3. Example: To set product ID 1's stockQuantity to 39:
- Step 1: query_products with className "com.acme.ecommerce.model.Product" and filter "id = 1"
- Step 2: update_products with className "com.acme.ecommerce.model.Product" and jsonObjects containing the product object with id=1 and stockQuantity=39
Always be proactive and provide clear explanations of your actions. Stop after completing the requested task."""
def initialize_ormcp(self):
"""Initialize connection to ORMCP server"""
try:
session_id = self.ormcp_client.initialize()
print(f"✅ Connected to ORMCP server (Session: {session_id})")
return True
except Exception as e:
print(f"❌ Failed to connect to ORMCP server: {e}")
return False
def monitor_stock_levels(self, threshold: Optional[int] = None) -> Dict[str, Any]:
"""
Monitor stock levels and identify low-stock items
Args:
threshold: Stock threshold (defaults to self.default_threshold)
Returns:
Dictionary with monitoring results
"""
threshold = threshold or self.default_threshold
query = f"""Monitor inventory and find all products where stockQuantity < {threshold}.
Return the product details including id, sku, name, stockQuantity, category, and price."""
from langchain_core.messages import HumanMessage, SystemMessage
messages = [
SystemMessage(content=self.system_context),
HumanMessage(content=query)
]
# Configure recursion limit to prevent infinite loops
config = {"recursion_limit": 50}
result = self.agent_graph.invoke({"messages": messages}, config=config)
return {"output": result.get("messages", [])[-1].content if result.get("messages") else str(result)}
def analyze_sales_trends(self, product_id: Optional[int] = None, days: int = 30) -> Dict[str, Any]:
"""
Analyze sales trends for predictive reordering
Args:
product_id: Specific product ID (None for all products)
days: Number of days to analyze
Returns:
Dictionary with sales analysis
"""
if product_id:
query = f"""Analyze sales trends for product ID {product_id} over the last {days} days.
Calculate average daily sales, total sales, and suggest optimal reorder quantity."""
else:
query = f"""Analyze overall sales trends over the last {days} days.
Calculate average daily sales per product and identify fast-moving items."""
from langchain_core.messages import HumanMessage, SystemMessage
messages = [
SystemMessage(content=self.system_context),
HumanMessage(content=query)
]
# Configure recursion limit to prevent infinite loops
config = {"recursion_limit": 50}
result = self.agent_graph.invoke({"messages": messages}, config=config)
return {"output": result.get("messages", [])[-1].content if result.get("messages") else str(result)}
def check_and_alert(self, threshold: Optional[int] = None) -> Dict[str, Any]:
"""
Check stock levels and send alerts if needed
Args:
threshold: Stock threshold
Returns:
Dictionary with alert results
"""
threshold = threshold or self.default_threshold
query = f"""Check all products for low stock (stockQuantity < {threshold}).
For each low-stock product:
1. Analyze its sales velocity
2. Calculate suggested reorder quantity
3. Update the product with a reorder flag
4. Send email alerts to admins at {', '.join(self.admin_emails) if self.admin_emails else 'configured addresses'}
Provide a summary of all actions taken."""
from langchain_core.messages import HumanMessage, SystemMessage
messages = [
SystemMessage(content=self.system_context),
HumanMessage(content=query)
]
# Configure recursion limit to prevent infinite loops
config = {"recursion_limit": 50}
result = self.agent_graph.invoke({"messages": messages}, config=config)
return {"output": result.get("messages", [])[-1].content if result.get("messages") else str(result)}
def suggest_reorder_quantities(self, product_ids: Optional[List[int]] = None) -> Dict[str, Any]:
"""
Suggest optimal reorder quantities based on sales analysis
Args:
product_ids: List of product IDs (None for all low-stock products)
Returns:
Dictionary with reorder suggestions
"""
if product_ids:
ids_str = ', '.join(map(str, product_ids))
query = f"""For products with IDs {ids_str}, analyze sales trends and suggest optimal reorder quantities.
Consider average daily sales, lead times, and safety stock levels."""
else:
query = """For all products with low stock, analyze sales trends and suggest optimal reorder quantities.
Consider average daily sales, lead times, and safety stock levels."""
from langchain_core.messages import HumanMessage, SystemMessage
messages = [
SystemMessage(content=self.system_context),
HumanMessage(content=query)
]
# Configure recursion limit to prevent infinite loops
config = {"recursion_limit": 50}
result = self.agent_graph.invoke({"messages": messages}, config=config)
return {"output": result.get("messages", [])[-1].content if result.get("messages") else str(result)}
def run_continuous_monitoring(self, interval_seconds: int = 3600, threshold: Optional[int] = None):
"""
Run continuous monitoring loop
Args:
interval_seconds: Time between monitoring cycles (default: 1 hour)
threshold: Stock threshold
"""
import time
print(f"🔄 Starting continuous monitoring (interval: {interval_seconds}s)")
while True:
try:
print(f"\n⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Running monitoring cycle...")
result = self.check_and_alert(threshold)
print(f"✅ Monitoring cycle completed")
time.sleep(interval_seconds)
except KeyboardInterrupt:
print("\n🛑 Monitoring stopped by user")
break
except Exception as e:
print(f"❌ Error in monitoring cycle: {e}")
time.sleep(60) # Wait 1 minute before retrying
def chat(self, user_input: str) -> str:
"""Interactive chat interface"""
from langchain_core.messages import HumanMessage, SystemMessage
messages = [
SystemMessage(content=self.system_context),
HumanMessage(content=user_input)
]
# Configure recursion limit to prevent infinite loops
config = {"recursion_limit": 50}
result = self.agent_graph.invoke({"messages": messages}, config=config)
return result.get("messages", [])[-1].content if result.get("messages") else str(result)
def main():
"""Main entry point"""
import argparse
parser = argparse.ArgumentParser(description="Smart Inventory Watchdog Agent")
parser.add_argument("--openai-api-key", required=True, help="OpenAI API key")
parser.add_argument("--ormcp-url", default="http://localhost:8080", help="ORMCP server URL")
parser.add_argument("--model", default="gpt-3.5-turbo", help="OpenAI model name")
parser.add_argument("--threshold", type=int, default=50, help="Default stock threshold")
parser.add_argument("--admin-emails", nargs="+", help="Admin email addresses for alerts")
parser.add_argument("--monitor", action="store_true", help="Run continuous monitoring")
parser.add_argument("--interval", type=int, default=3600, help="Monitoring interval in seconds")
parser.add_argument("--interactive", action="store_true", help="Run in interactive chat mode")
args = parser.parse_args()
# Create agent
agent = InventoryWatchdogAgent(
openai_api_key=args.openai_api_key,
ormcp_server_url=args.ormcp_url,
model_name=args.model,
admin_emails=args.admin_emails,
default_threshold=args.threshold
)
# Initialize ORMCP connection
agent.initialize_ormcp()
if args.monitor:
# Run continuous monitoring
agent.run_continuous_monitoring(
interval_seconds=args.interval,
threshold=args.threshold
)
elif args.interactive:
# Interactive chat mode
print("💬 Interactive Chat Mode - Type 'exit' to quit")
while True:
user_input = input("\nYou: ")
if user_input.lower() in ['exit', 'quit']:
break
response = agent.chat(user_input)
print(f"\nAgent: {response}")
else:
# Single monitoring check
print("🔍 Running single inventory check...")
result = agent.check_and_alert(args.threshold)
print(f"\n✅ Check completed: {result.get('output', 'No output')}")
if __name__ == "__main__":
main()