-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo_test.py
More file actions
216 lines (186 loc) · 7.95 KB
/
Copy pathdemo_test.py
File metadata and controls
216 lines (186 loc) · 7.95 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
"""
ASI Supply Chain - Complete System Demo & Test
This script demonstrates all agent capabilities for the bounty submission
"""
import asyncio
import json
from datetime import datetime
from uagents import Agent, Context
from uagents.setup import fund_agent_if_low
from models.supply_chain_models import (
InventoryStatusRequest,
InventoryStatus,
DeliveryRequest,
OptimizedRoute,
DemandQuery,
DemandForecast
)
# Agent addresses (fill these from your running agents)
INVENTORY_AGENT = "agent1qvjr0s6phucjm90qhmq2eud0l2njeql77fsjq9vz4zlfhqtw8nc5k2ru9fq"
ROUTE_AGENT = "agent1qvufwnmetz0u92yzw7ls8lh2utumwcd87fr78y7nhdg0mllgdd0tuhc3njm"
DEMAND_AGENT = "agent1qfj4m84me57yggpq0qpetwga6rrdkhldv8kf7ap3zwx9c9tzshkscmqdajd"
COORDINATOR_AGENT = "agent1q0j0ara7acrf2jr9nvcxtxvv5ptjt0gl0jrlmrlvrz8tqdaumq2cysr49g9"
# Demo test agent
demo_agent = Agent(
name="demo_tester",
seed="demo_test_seed_12345",
port=8888,
endpoint=["http://localhost:8888/submit"]
)
test_results = {
"inventory_test": {"status": "pending", "response": None},
"route_test": {"status": "pending", "response": None},
"demand_test": {"status": "pending", "response": None}
}
print("\n" + "="*70)
print("[*] ASI SUPPLY CHAIN - SYSTEM DEMONSTRATION")
print("="*70)
print("\n[*] Testing all agent capabilities...\n")
@demo_agent.on_event("startup")
async def start_tests(ctx: Context):
"""Run all system tests on startup"""
print("[*] STARTING AGENT COMMUNICATION TESTS...\n")
# Test 1: Inventory Monitor
print("="*70)
print("[TEST 1] INVENTORY MONITOR")
print("="*70)
print("[*] Requesting inventory status for warehouse WH001...")
inventory_request = InventoryStatusRequest(warehouse_id="WH001")
await ctx.send(INVENTORY_AGENT, inventory_request)
await asyncio.sleep(3)
# Test 2: Route Optimizer
print("\n" + "="*70)
print("[TEST 2] ROUTE OPTIMIZER")
print("="*70)
print("[*] Requesting optimal route from WH001 to DEST_1...")
route_request = DeliveryRequest(
order_id="TEST_ORDER_001",
origin="WH001",
destination="DEST_1",
cargo_weight=150.0,
urgency="high"
)
await ctx.send(ROUTE_AGENT, route_request)
await asyncio.sleep(3)
# Test 3: Demand Predictor with MeTTa
print("\n" + "="*70)
print("[TEST 3] DEMAND PREDICTOR (MeTTa AI)")
print("="*70)
print("[*] Requesting demand forecast for 'laptop' in Q4...")
demand_request = DemandQuery(
product_id="laptop",
time_period="Q4",
warehouse_id="WH001",
historical_data={"2024-Q1": 100, "2024-Q2": 120, "2024-Q3": 115}
)
await ctx.send(DEMAND_AGENT, demand_request)
await asyncio.sleep(5)
# Print results summary
await asyncio.sleep(2)
print_test_summary()
# Handle Inventory Response
@demo_agent.on_message(model=InventoryStatus)
async def handle_inventory_response(ctx: Context, sender: str, msg: InventoryStatus):
"""Receive and display inventory status"""
try:
print("\n[OK] INVENTORY RESPONSE RECEIVED:")
print(f" - Warehouse: {msg.warehouse_id if hasattr(msg, 'warehouse_id') else 'Unknown'}")
if hasattr(msg, 'products'):
print(f" - Products in stock:")
for product, quantity in msg.products.items():
status = "[OK]" if quantity > 50 else "[LOW]"
print(f" * {product}: {quantity} units {status}")
test_results["inventory_test"]["status"] = "success"
test_results["inventory_test"]["response"] = str(msg)
except Exception as e:
print(f"❌ Error processing inventory response: {e}")
test_results["inventory_test"]["status"] = "error"
# Handle Route Response
@demo_agent.on_message(model=OptimizedRoute)
async def handle_route_response(ctx: Context, sender: str, msg: OptimizedRoute):
"""Receive and display optimized route"""
try:
print("\n[OK] ROUTE OPTIMIZATION RESPONSE RECEIVED:")
if hasattr(msg, 'route'):
print(f" - Route: {' -> '.join(msg.route)}")
if hasattr(msg, 'estimated_cost'):
print(f" - Cost: ${msg.estimated_cost:.2f}")
if hasattr(msg, 'estimated_time'):
print(f" - Time: {msg.estimated_time:.1f} hours")
if hasattr(msg, 'carrier'):
print(f" - Carrier: {msg.carrier}")
if hasattr(msg, 'reasoning'):
print(f" - Reasoning: {msg.reasoning}")
test_results["route_test"]["status"] = "success"
test_results["route_test"]["response"] = str(msg)
except Exception as e:
print(f"❌ Error processing route response: {e}")
test_results["route_test"]["status"] = "error"
# Handle Demand Response
@demo_agent.on_message(model=DemandForecast)
async def handle_demand_response(ctx: Context, sender: str, msg: DemandForecast):
"""Receive and display demand forecast with MeTTa reasoning"""
try:
print("\n[OK] DEMAND FORECAST RESPONSE RECEIVED (MeTTa AI):")
if hasattr(msg, 'product_id'):
print(f" - Product: {msg.product_id}")
if hasattr(msg, 'predicted_demand'):
print(f" - Forecast: {msg.predicted_demand.upper()}")
if hasattr(msg, 'confidence'):
confidence_bar = "#" * int(msg.confidence * 10) + "." * (10 - int(msg.confidence * 10))
print(f" - Confidence: [{confidence_bar}] {msg.confidence:.0%}")
if hasattr(msg, 'recommendation'):
print(f" - Recommendation: {msg.recommendation}")
if hasattr(msg, 'reasoning'):
print(f"\n [METTA AI REASONING]:")
for line in msg.reasoning.split('\n'):
if line.strip():
print(f" {line}")
if hasattr(msg, 'seasonal_factors') and msg.seasonal_factors:
print(f"\n [SEASONAL FACTORS]:")
for factor in msg.seasonal_factors:
print(f" * {factor}")
test_results["demand_test"]["status"] = "success"
test_results["demand_test"]["response"] = str(msg)
except Exception as e:
print(f"[ERROR] Error processing demand response: {e}")
test_results["demand_test"]["status"] = "error"
def print_test_summary():
"""Print final test results summary"""
print("\n" + "="*70)
print("[RESULTS] TEST SUMMARY")
print("="*70)
total_tests = len(test_results)
successful_tests = sum(1 for result in test_results.values() if result["status"] == "success")
for test_name, result in test_results.items():
status_icon = "[OK]" if result["status"] == "success" else "[ERROR]" if result["status"] == "error" else "[PENDING]"
print(f"{status_icon} {test_name.replace('_', ' ').title()}: {result['status'].upper()}")
print("\n" + "="*70)
print(f"[SCORE] {successful_tests}/{total_tests} tests passed")
print("="*70)
if successful_tests == total_tests:
print("\n[SUCCESS] ALL SYSTEMS OPERATIONAL!")
print("[SUCCESS] Your multi-agent system is working perfectly!")
print("\n[ACHIEVEMENTS]:")
print(" * 4 Autonomous agents communicating")
print(" * Fetch.ai uAgents framework integrated")
print(" * MeTTa knowledge graph reasoning")
print(" * Real-time inventory monitoring")
print(" * Route optimization with Dijkstra")
print(" * Explainable AI demand forecasting")
print("\n[INFO] Ready for ASI Alliance Bounty submission!")
else:
print("\n[WARNING] Some tests failed. Check agent logs for details.")
print("\n" + "="*70 + "\n")
if __name__ == "__main__":
print("\n[CONFIG] Agent Addresses:")
print(f" * Inventory Agent: {INVENTORY_AGENT[:20]}...")
print(f" * Route Agent: {ROUTE_AGENT[:20]}...")
print(f" * Demand Agent: {DEMAND_AGENT[:20]}...")
print(f" * Coordinator: {COORDINATOR_AGENT[:20]}...")
print()
try:
demo_agent.run()
except KeyboardInterrupt:
print("\n\n[WARNING] Demo interrupted by user")
print_test_summary()