-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
565 lines (451 loc) · 24.6 KB
/
server.py
File metadata and controls
565 lines (451 loc) · 24.6 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
"""
Smart Home — Agent-to-Agent Communication Demo
5 independent agents, each with their own model, expertise, and context.
They self-organize via Agent Relay channels and DMs.
Architecture:
#smarthome channel — Home Controller posts here, specialists listen
Each specialist only picks up commands matching their expertise
QA Monitor watches everything and scores responses
Agents:
1. Home Controller (free model) — receives commands, routes to device agents
2. Climate Agent (gpt-4o-mini) — has thermostat data from Ecobee/Nest
3. Security Agent (gpt-4o-mini) — has camera feeds from Ring, alarm from ADT
4. Lighting Agent (free model) — has Hue/LIFX scene data
5. Energy Monitor (free model) — tracks usage, suggests optimizations
"""
import asyncio
import json
import os
import uuid
import string
import random
import time
from datetime import datetime
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from agent_relay.communicate import Relay
from agent_relay.communicate.types import RelayConfig, Message
from integrations.context_loader import get_context
app = FastAPI()
RUN_ID = uuid.uuid4().hex[:4]
CFG = RelayConfig(
workspace=os.environ.get("RELAY_WORKSPACE", "demo"),
api_key=os.environ.get("RELAY_API_KEY", "demo-key"),
base_url=os.environ.get("RELAY_BASE_URL", "https://api.relaycast.dev"),
)
CHANNEL = f"smarthome-{RUN_ID}"
API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
BASE_URL = "https://openrouter.ai/api/v1"
# Agent names
CONTROLLER = f"controller-{RUN_ID}"
CLIMATE = f"climate-{RUN_ID}"
SECURITY = f"security-{RUN_ID}"
LIGHTING = f"lighting-{RUN_ID}"
ENERGY = f"energy-{RUN_ID}"
# Models — the cost story
FREE_MODEL = "nvidia/nemotron-3-nano-30b-a3b:free"
SMART_MODEL = "openai/gpt-4o-mini"
# Context is now loaded dynamically from integrations/context_loader.py
# In demo mode: rich simulated data. In production: real Nango integrations.
ws_clients: list[WebSocket] = []
command_queue: asyncio.Queue = asyncio.Queue()
agent_online_events: list[dict] = []
relays: dict[str, Relay] = {}
# Stats
stats = {"total":0,"simple":0,"routed":0,"ctrl_tokens":0,"sp_tokens":0,"qa_tokens":0,
"ctrl_cost":0.0,"sp_cost":0.0,"qa_cost":0.0,"mono_cost":0.0}
async def broadcast(event: dict):
msg = json.dumps(event)
for ws in ws_clients[:]:
try: await ws.send_text(msg)
except: ws_clients.remove(ws)
def cmd_id():
return "CMD-" + "".join(random.choices(string.ascii_uppercase + string.digits, k=6))
async def llm(model, system, user, label="") -> dict:
if not API_KEY:
await asyncio.sleep(0.8)
return {"content":f"[Simulated {label}]","model":model,"tokens":50,"cost":0,"ms":800}
import httpx
t0 = time.time()
try:
async with httpx.AsyncClient(timeout=30) as c:
r = await c.post(f"{BASE_URL}/chat/completions",
headers={"Authorization":f"Bearer {API_KEY}"},
json={"model":model,"messages":[
{"role":"system","content":system},
{"role":"user","content":user}
],"max_tokens":800})
ms = int((time.time()-t0)*1000)
if r.status_code != 200:
return {"content":f"[Model {r.status_code}]","model":model,"tokens":0,"cost":0,"ms":ms}
d = r.json()
msg = d["choices"][0]["message"]
content = msg.get("content") or msg.get("reasoning") or ""
if not content and msg.get("reasoning_details"):
content = msg["reasoning_details"][0].get("text","")
usage = d.get("usage",{})
return {"content":content or "[No response]","model":d.get("model",model),
"tokens":usage.get("total_tokens",0),"cost":float(usage.get("cost",0)),"ms":ms}
except Exception as e:
return {"content":f"[Error: {e}]","model":model,"tokens":0,"cost":0,"ms":int((time.time()-t0)*1000)}
# ============================================================
# AGENT 1: HOME CONTROLLER (Router)
# ============================================================
async def agent_controller():
r = Relay(CONTROLLER, CFG); await r.__aenter__(); relays[CONTROLLER] = r
ev = {"type":"agent_online","agent":"Home Controller","name":CONTROLLER,"model":FREE_MODEL,
"role":"Command Router","color":"emerald",
"desc":"Fast free model. Classifies commands and routes to the right device agent via #smarthome channel."}
agent_online_events.append(ev); await broadcast(ev)
# Listen for specialist responses
def on_msg(msg):
if msg.sender == CONTROLLER: return
asyncio.create_task(_ctrl_got_response(msg))
r.on_message(on_msg)
while True:
command = await command_queue.get()
asyncio.create_task(_route_command(command))
async def _route_command(t):
tid, user, query = t["command_id"], t["user"], t["query"]
stats["total"] += 1
await broadcast({"type":"thinking","agent":"Home Controller","color":"emerald","tid":tid,
"detail":f"Processing {user}'s command...","model":FREE_MODEL})
res = await llm(FREE_MODEL,
"""You are a smart home controller. Classify this command into exactly ONE category:
- "climate" (temperature, thermostat, heating, cooling, HVAC, humidity)
- "security" (locks, cameras, alarm, arm, disarm, doors, motion)
- "lighting" (lights, lamps, brightness, scenes, colors, dim)
- "energy" (power usage, electricity, solar, bills, consumption, efficiency)
- "simple" (status check, general question, greeting)
Respond ONLY with JSON: {"category":"...", "urgency":"low|medium|high", "summary":"one line summary"}""",
f"User {user}: {query}", "Route")
stats["ctrl_tokens"] += res["tokens"]; stats["ctrl_cost"] += res["cost"]
await broadcast({"type":"model_used","agent":"Home Controller","color":"emerald",
"model":res["model"],"tokens":res["tokens"],"cost":res["cost"],"ms":res["ms"]})
# Parse category
cat = "simple"
for kw, c in [("temp","climate"),("thermo","climate"),("heat","climate"),("cool","climate"),("hvac","climate"),
("lock","security"),("camera","security"),("alarm","security"),("arm","security"),("door","security"),
("light","lighting"),("lamp","lighting"),("bright","lighting"),("dim","lighting"),("scene","lighting"),
("energy","energy"),("power","energy"),("solar","energy"),("usage","energy"),("electric","energy"),("bill","energy")]:
if kw in query.lower(): cat = c; break
try:
p = json.loads(res["content"])
cat = p.get("category", cat)
urgency = p.get("urgency", "medium")
summary = p.get("summary", query[:80])
except:
urgency = "medium"; summary = query[:80]
if cat == "simple":
stats["simple"] += 1
ans = await llm(FREE_MODEL, "You are a smart home assistant. Answer concisely about home status.",
f"User asks: {query}", "Direct answer")
stats["ctrl_tokens"] += ans["tokens"]; stats["ctrl_cost"] += ans["cost"]
stats["mono_cost"] += 0.00015 * ((res["tokens"]+ans["tokens"])/1000)
await broadcast({"type":"route_result","tid":tid,"action":"direct","category":cat,
"response":ans["content"],"cost_saved":True})
await broadcast({"type":"complete","tid":tid,"resolved_by":"Home Controller (direct — free model)",
"cost_note":"$0 — handled entirely by free model"})
await _send_stats(); return
stats["routed"] += 1
stats["mono_cost"] += 0.00015 * (res["tokens"]/1000)
await broadcast({"type":"route_result","tid":tid,"action":"route","category":cat,
"urgency":urgency,"summary":summary})
# POST TO CHANNEL — this is the key moment
payload = json.dumps({"command_id":tid,"user":user,"query":query,
"category":cat,"urgency":urgency,"summary":summary})
await broadcast({"type":"channel_post","from":"Home Controller","from_name":CONTROLLER,
"channel":CHANNEL,"tid":tid,
"detail":f"[{cat.upper()}] {urgency} priority — {summary}"})
await relays[CONTROLLER].post(CHANNEL, payload)
async def _ctrl_got_response(msg):
try: d = json.loads(msg.text)
except: d = {"response":str(msg.text),"command_id":"?"}
tid = d.get("command_id","?")
await broadcast({"type":"relay_dm","from_agent":msg.sender,"to_agent":"Home Controller",
"to_name":CONTROLLER,"tid":tid,
"preview":f"Response: {str(d.get('response',''))[:80]}..."})
await broadcast({"type":"followup","tid":tid,
"detail":f"Home Controller received response and updated home state."})
await broadcast({"type":"complete","tid":tid,
"resolved_by":f"{msg.sender} → Home Controller"})
await _send_stats()
# ============================================================
# AGENT 2: CLIMATE AGENT
# ============================================================
async def agent_climate():
r = Relay(CLIMATE, CFG); await r.__aenter__(); relays[CLIMATE] = r
ev = {"type":"agent_online","agent":"Climate Agent","name":CLIMATE,"model":SMART_MODEL,
"role":"HVAC & Temperature","color":"amber",
"desc":"Premium model with Ecobee/Nest data. Controls thermostat, manages schedules, optimizes comfort."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == CLIMATE: return
asyncio.create_task(_climate_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _climate_handle(msg):
try: d = json.loads(msg.text)
except: return
if d.get("category") != "climate": return
tid, user, query = d["command_id"], d["user"], d["query"]
await broadcast({"type":"specialist_pickup","agent":"Climate Agent","color":"amber",
"tid":tid,"detail":f"Picking up climate command — I have {user}'s thermostat data"})
await broadcast({"type":"thinking","agent":"Climate Agent","color":"amber","tid":tid,
"detail":"Checking thermostat zones and HVAC status...","model":SMART_MODEL})
ctx = await get_context("climate", user, query)
await broadcast({"type":"context_loaded","agent":"Climate Agent","tid":tid,
"sources":ctx["sources"],"is_live":ctx["is_live"]})
res = await llm(SMART_MODEL,
f"""You are a climate control specialist with access to thermostat and HVAC data.
{ctx['context_text']}
Provide a thorough response referencing SPECIFIC data from above (temperatures, zones, schedules).
Address the user by name. Explain what actions you're taking and why.
If adjusting temperature, mention the current vs new settings.""",
f"User {user}: {query}", "Climate")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += res["cost"]
await broadcast({"type":"model_used","agent":"Climate Agent","color":"amber",
"model":res["model"],"tokens":res["tokens"],"cost":res["cost"],"ms":res["ms"]})
await broadcast({"type":"resolution","agent":"Climate Agent","color":"amber",
"tid":tid,"text":res["content"]})
await broadcast({"type":"relay_dm","from_agent":"Climate Agent","from_name":CLIMATE,
"to_agent":"Home Controller","to_name":CONTROLLER,"tid":tid,
"preview":f"Climate resolved: {res['content'][:80]}..."})
await relays[CLIMATE].send(CONTROLLER, json.dumps({"command_id":tid,"user":user,
"response":res["content"],"agent":"Climate Agent"}))
await relays[CLIMATE].post(CHANNEL, json.dumps({"type":"resolution","command_id":tid,
"agent":"Climate Agent","resolution":res["content"],"user":user}))
# ============================================================
# AGENT 3: SECURITY AGENT
# ============================================================
async def agent_security():
r = Relay(SECURITY, CFG); await r.__aenter__(); relays[SECURITY] = r
ev = {"type":"agent_online","agent":"Security Agent","name":SECURITY,"model":SMART_MODEL,
"role":"Cameras & Alarms","color":"red",
"desc":"Premium model with Ring/ADT data. Manages cameras, locks, alarm system, motion alerts."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == SECURITY: return
asyncio.create_task(_security_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _security_handle(msg):
try: d = json.loads(msg.text)
except: return
if d.get("category") != "security": return
tid, user, query = d["command_id"], d["user"], d["query"]
await broadcast({"type":"specialist_pickup","agent":"Security Agent","color":"red",
"tid":tid,"detail":f"🚨 Security command — checking {user}'s cameras and locks"})
await broadcast({"type":"thinking","agent":"Security Agent","color":"red","tid":tid,
"detail":"Scanning cameras, checking door sensors, reviewing activity log...","model":SMART_MODEL})
ctx = await get_context("security", user, query)
await broadcast({"type":"context_loaded","agent":"Security Agent","tid":tid,
"sources":ctx["sources"],"is_live":ctx["is_live"]})
res = await llm(SMART_MODEL,
f"""You are a home security specialist with access to camera feeds and alarm data.
{ctx['context_text']}
This may be urgent. Reference SPECIFIC data from above (camera status, door states, activity log).
Address the user by name. Detail:
1. Current security status
2. Actions taken (arm/disarm, lock/unlock, etc)
3. Any alerts or concerns
Be reassuring but thorough.""",
f"User {user}: {query}", "Security")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += res["cost"]
await broadcast({"type":"model_used","agent":"Security Agent","color":"red",
"model":res["model"],"tokens":res["tokens"],"cost":res["cost"],"ms":res["ms"]})
await broadcast({"type":"resolution","agent":"Security Agent","color":"red",
"tid":tid,"text":res["content"]})
await broadcast({"type":"relay_dm","from_agent":"Security Agent","from_name":SECURITY,
"to_agent":"Home Controller","to_name":CONTROLLER,"tid":tid,
"preview":f"Security resolved: {res['content'][:80]}..."})
await relays[SECURITY].send(CONTROLLER, json.dumps({"command_id":tid,"user":user,
"response":res["content"],"agent":"Security Agent"}))
await relays[SECURITY].post(CHANNEL, json.dumps({"type":"resolution","command_id":tid,
"agent":"Security Agent","resolution":res["content"],"user":user}))
# ============================================================
# AGENT 4: LIGHTING AGENT
# ============================================================
async def agent_lighting():
r = Relay(LIGHTING, CFG); await r.__aenter__(); relays[LIGHTING] = r
ev = {"type":"agent_online","agent":"Lighting Agent","name":LIGHTING,"model":FREE_MODEL,
"role":"Lights & Scenes","color":"blue",
"desc":"Free model with Hue/LIFX data. Controls lights, activates scenes, manages brightness and colors."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == LIGHTING: return
asyncio.create_task(_lighting_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _lighting_handle(msg):
try: d = json.loads(msg.text)
except: return
if d.get("category") != "lighting": return
tid, user, query = d["command_id"], d["user"], d["query"]
await broadcast({"type":"specialist_pickup","agent":"Lighting Agent","color":"blue",
"tid":tid,"detail":f"Picking up lighting command — I have {user}'s Hue/LIFX data"})
await broadcast({"type":"thinking","agent":"Lighting Agent","color":"blue","tid":tid,
"detail":"Checking light status and available scenes...","model":FREE_MODEL})
ctx = await get_context("lighting", user, query)
await broadcast({"type":"context_loaded","agent":"Lighting Agent","tid":tid,
"sources":ctx["sources"],"is_live":ctx["is_live"]})
res = await llm(FREE_MODEL,
f"""You are a lighting specialist with access to Hue and LIFX smart light data.
{ctx['context_text']}
Reference SPECIFIC data from above (room states, scenes, bulb counts).
Address the user by name. Provide:
1. What changes you're making
2. Current vs new state
3. Suggest relevant scenes if applicable""",
f"User {user}: {query}", "Lighting")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += 0.00015 * (res["tokens"]/1000)
await broadcast({"type":"model_used","agent":"Lighting Agent","color":"blue",
"model":res["model"],"tokens":res["tokens"],"cost":res["cost"],"ms":res["ms"]})
await broadcast({"type":"resolution","agent":"Lighting Agent","color":"blue",
"tid":tid,"text":res["content"]})
await broadcast({"type":"relay_dm","from_agent":"Lighting Agent","from_name":LIGHTING,
"to_agent":"Home Controller","to_name":CONTROLLER,"tid":tid,
"preview":f"Lighting resolved: {res['content'][:80]}..."})
await relays[LIGHTING].send(CONTROLLER, json.dumps({"command_id":tid,"user":user,
"response":res["content"],"agent":"Lighting Agent"}))
await relays[LIGHTING].post(CHANNEL, json.dumps({"type":"resolution","command_id":tid,
"agent":"Lighting Agent","resolution":res["content"],"user":user}))
# ============================================================
# AGENT 5: ENERGY MONITOR
# ============================================================
async def agent_energy():
r = Relay(ENERGY, CFG); await r.__aenter__(); relays[ENERGY] = r
ev = {"type":"agent_online","agent":"Energy Monitor","name":ENERGY,"model":FREE_MODEL,
"role":"Usage & Optimization","color":"slate",
"desc":"Free model. Monitors energy usage via Sense, tracks costs, suggests efficiency optimizations."}
agent_online_events.append(ev); await broadcast(ev)
def on_msg(msg):
if msg.sender == ENERGY: return
asyncio.create_task(_energy_handle(msg))
r.on_message(on_msg)
while True: await asyncio.sleep(60)
async def _energy_handle(msg):
try: d = json.loads(msg.text)
except: return
# Energy monitor also reviews resolutions for efficiency tips
if d.get("type") == "resolution":
await _energy_review(d)
return
if d.get("category") != "energy": return
tid, user, query = d["command_id"], d["user"], d["query"]
await broadcast({"type":"specialist_pickup","agent":"Energy Monitor","color":"slate",
"tid":tid,"detail":f"Checking {user}'s energy data and usage patterns"})
await broadcast({"type":"thinking","agent":"Energy Monitor","color":"slate","tid":tid,
"detail":"Analyzing real-time usage, rates, and optimization opportunities...","model":FREE_MODEL})
ctx = await get_context("energy", user, query)
await broadcast({"type":"context_loaded","agent":"Energy Monitor","tid":tid,
"sources":ctx["sources"],"is_live":ctx["is_live"]})
res = await llm(FREE_MODEL,
f"""You are an energy monitoring specialist with access to real-time power data and utility rates.
{ctx['context_text']}
Reference SPECIFIC data from above (wattage, costs, rates, device consumption).
Address the user by name. Provide:
1. Current usage summary
2. Answer their specific question
3. Cost-saving recommendations based on their data""",
f"User {user}: {query}", "Energy")
stats["sp_tokens"] += res["tokens"]; stats["sp_cost"] += res["cost"]
stats["mono_cost"] += 0.00015 * (res["tokens"]/1000)
await broadcast({"type":"model_used","agent":"Energy Monitor","color":"slate",
"model":res["model"],"tokens":res["tokens"],"cost":res["cost"],"ms":res["ms"]})
await broadcast({"type":"resolution","agent":"Energy Monitor","color":"slate",
"tid":tid,"text":res["content"]})
await broadcast({"type":"relay_dm","from_agent":"Energy Monitor","from_name":ENERGY,
"to_agent":"Home Controller","to_name":CONTROLLER,"tid":tid,
"preview":f"Energy resolved: {res['content'][:80]}..."})
await relays[ENERGY].send(CONTROLLER, json.dumps({"command_id":tid,"user":user,
"response":res["content"],"agent":"Energy Monitor"}))
await relays[ENERGY].post(CHANNEL, json.dumps({"type":"resolution","command_id":tid,
"agent":"Energy Monitor","resolution":res["content"],"user":user}))
async def _energy_review(d):
"""Energy Monitor also acts as QA — reviews other agents' actions for efficiency impact."""
tid = d.get("command_id","?")
agent = d.get("agent","Unknown")
resolution = d.get("resolution","")
user = d.get("user","")
await broadcast({"type":"thinking","agent":"Energy Monitor","color":"slate","tid":tid,
"detail":f"Reviewing {agent}'s action for energy impact...","model":FREE_MODEL})
res = await llm(FREE_MODEL,
"""You are an energy efficiency reviewer. Score this smart home action on 3 criteria (1-5 each):
- Efficiency: Does this action optimize energy usage?
- Comfort: Does it maintain or improve comfort?
- Cost: Is this cost-effective given current rates?
Respond ONLY with JSON: {"efficiency":N,"comfort":N,"cost":N,"overall":N,"note":"one sentence tip"}""",
f"Agent: {agent}\nUser: {user}\nAction: {resolution[:500]}", "QA")
stats["qa_tokens"] += res["tokens"]; stats["qa_cost"] += res["cost"]
try:
scores = json.loads(res["content"])
except:
scores = {"efficiency":4,"comfort":4,"cost":4,"overall":4,"note":"Good home automation action"}
await broadcast({"type":"qa_score","tid":tid,"agent":agent,"scores":scores,
"model":res["model"],"tokens":res["tokens"]})
async def _send_stats():
multi = stats["ctrl_cost"] + stats["sp_cost"] + stats["qa_cost"]
mono = stats["mono_cost"]
pct = ((mono - multi) / mono * 100) if mono > 0 else 0
await broadcast({"type":"stats",
"total":stats["total"],"simple":stats["simple"],"routed":stats["routed"],
"ctrl_tokens":stats["ctrl_tokens"],"sp_tokens":stats["sp_tokens"],"qa_tokens":stats["qa_tokens"],
"multi_cost":round(multi,6),"mono_cost":round(mono,6),"savings_pct":round(pct,1)})
# ============================================================
# STARTUP
# ============================================================
@app.on_event("startup")
async def startup():
asyncio.create_task(agent_controller())
await asyncio.sleep(2)
asyncio.create_task(agent_climate())
await asyncio.sleep(2)
asyncio.create_task(agent_security())
await asyncio.sleep(2)
asyncio.create_task(agent_lighting())
await asyncio.sleep(2)
asyncio.create_task(agent_energy())
@app.on_event("shutdown")
async def shutdown():
for r in relays.values():
try: await r.__aexit__(None,None,None)
except: pass
@app.get("/")
async def index():
return FileResponse(Path(__file__).parent / "index.html")
@app.post("/api/submit")
async def submit(data: dict):
q = data.get("query",""); u = data.get("user","Homeowner")
if not q: return {"error":"query required"}
tid = cmd_id()
await broadcast({"type":"command_created","tid":tid,"user":u,"query":q,
"timestamp":datetime.now().strftime("%H:%M:%S")})
await command_queue.put({"query":q,"user":u,"command_id":tid})
return {"status":"processing","command_id":tid}
@app.websocket("/ws")
async def ws_ep(ws: WebSocket):
await ws.accept(); ws_clients.append(ws)
for ev in agent_online_events:
await ws.send_text(json.dumps(ev))
try:
while True: await ws.receive_text()
except WebSocketDisconnect: ws_clients.remove(ws)
app.mount("/assets", StaticFiles(directory=Path(__file__).parent / "assets"), name="assets")
if __name__ == "__main__":
import uvicorn
print(f"\n🏠 Smart Home — Agent Relay Demo (5 agents)")
print(f" Controller: {CONTROLLER} ({FREE_MODEL})")
print(f" Climate: {CLIMATE} ({SMART_MODEL})")
print(f" Security: {SECURITY} ({SMART_MODEL})")
print(f" Lighting: {LIGHTING} ({FREE_MODEL})")
print(f" Energy: {ENERGY} ({FREE_MODEL})")
print(f" http://localhost:8083\n")
uvicorn.run(app, host="0.0.0.0", port=8083, log_level="warning")