-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent_process_manager.py
More file actions
1320 lines (1132 loc) · 54.6 KB
/
Copy pathagent_process_manager.py
File metadata and controls
1320 lines (1132 loc) · 54.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Agent Process Manager - Creates and manages autonomous agent processes with FastAPI servers
and Redis PubSub communication for self-improvement.
"""
import os
import sys
import json
import asyncio
import logging
import signal
import uuid
import time
import subprocess
import multiprocessing
from typing import Dict, List, Any, Optional, Set, Union, Callable
import psutil
import redis.asyncio as redis
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, Depends, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from pydantic import BaseModel, Field
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("agent-process-manager")
class AgentConfig(BaseModel):
"""Configuration for an agent process"""
agent_id: str = Field(default_factory=lambda: f"agent-{uuid.uuid4().hex[:8]}")
agent_name: str = Field(...)
agent_type: str = Field(...)
host: str = Field(default="127.0.0.1")
port: int = Field(...)
capabilities: List[str] = Field(default_factory=list)
model: str = Field(default="gpt-4")
command: Optional[str] = None
env_vars: Dict[str, str] = Field(default_factory=dict)
auto_restart: bool = Field(default=True)
memory_limit_mb: Optional[int] = None
cpu_limit_percent: Optional[int] = None
startup_timeout: int = Field(default=30)
max_restart_attempts: int = Field(default=3)
restart_delay: int = Field(default=5)
class AgentInfo(BaseModel):
"""Information about a running agent process"""
agent_id: str
agent_name: str
agent_type: str
host: str
port: int
url: str
capabilities: List[str]
status: str = "starting"
pid: Optional[int] = None
start_time: float = Field(default_factory=time.time)
last_heartbeat: float = Field(default_factory=time.time)
restart_count: int = 0
memory_usage_mb: Optional[float] = None
cpu_usage_percent: Optional[float] = None
health: Dict[str, Any] = Field(default_factory=dict)
class AgentProcessManager:
"""Manages agent processes with FastAPI servers and Redis PubSub communication"""
def __init__(self, redis_url=None, host="0.0.0.0", port=8500):
self.redis_url = redis_url or os.getenv("REDIS_URL", "redis://localhost:6379/0")
self.host = host
self.port = port
self.redis_client = None
self.pubsub = None
self.pubsub_task = None
self.agents: Dict[str, AgentInfo] = {}
self.processes: Dict[str, subprocess.Popen] = {}
self.websockets: Dict[str, WebSocket] = {}
self.app = FastAPI(title="Agent Process Manager")
self.setup_api()
self._shutdown_event = asyncio.Event()
self._health_check_task = None
self._monitor_task = None
logger.info(f"Agent Process Manager initialized on {host}:{port} with Redis URL: {self.redis_url}")
def setup_api(self):
"""Setup FastAPI routes and CORS middleware"""
# Add CORS middleware
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# API routes
@self.app.get("/")
async def root():
return {"status": "online", "service": "Agent Process Manager"}
@self.app.get("/health")
async def health_check():
return {
"status": "healthy",
"redis_connected": self.redis_client is not None,
"active_agents": len(self.agents),
"timestamp": time.time()
}
@self.app.get("/agents")
async def list_agents():
return {"agents": list(self.agents.values())}
@self.app.get("/agents/{agent_id}")
async def get_agent(agent_id: str):
if agent_id not in self.agents:
raise HTTPException(status_code=404, detail=f"Agent {agent_id} not found")
return self.agents[agent_id]
@self.app.post("/agents")
async def create_agent(agent_config: AgentConfig, background_tasks: BackgroundTasks):
# Check if port is already in use
for agent in self.agents.values():
if agent.port == agent_config.port:
raise HTTPException(status_code=400, detail=f"Port {agent_config.port} is already in use by agent {agent.agent_id}")
# Create agent info
agent_info = AgentInfo(
agent_id=agent_config.agent_id,
agent_name=agent_config.agent_name,
agent_type=agent_config.agent_type,
host=agent_config.host,
port=agent_config.port,
url=f"http://{agent_config.host}:{agent_config.port}",
capabilities=agent_config.capabilities
)
self.agents[agent_config.agent_id] = agent_info
# Start agent in background
background_tasks.add_task(self.start_agent_process, agent_config)
return agent_info
@self.app.delete("/agents/{agent_id}")
async def delete_agent(agent_id: str):
if agent_id not in self.agents:
raise HTTPException(status_code=404, detail=f"Agent {agent_id} not found")
# Stop agent process if running
if agent_id in self.processes:
await self.stop_agent_process(agent_id)
# Remove agent from agents dict
agent_info = self.agents.pop(agent_id)
# Publish agent stopped event
await self.publish_event("agent_stopped", {
"agent_id": agent_id,
"agent_name": agent_info.agent_name
})
return {"status": "success", "message": f"Agent {agent_id} deleted"}
@self.app.post("/agents/{agent_id}/restart")
async def restart_agent(agent_id: str, background_tasks: BackgroundTasks):
if agent_id not in self.agents:
raise HTTPException(status_code=404, detail=f"Agent {agent_id} not found")
# Stop agent process if running
if agent_id in self.processes:
await self.stop_agent_process(agent_id)
# Get agent config
agent_info = self.agents[agent_id]
agent_config = AgentConfig(
agent_id=agent_info.agent_id,
agent_name=agent_info.agent_name,
agent_type=agent_info.agent_type,
host=agent_info.host,
port=agent_info.port,
capabilities=agent_info.capabilities
)
# Start agent in background
background_tasks.add_task(self.start_agent_process, agent_config)
return {"status": "restarting", "agent_id": agent_id}
@self.app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
client_id = str(uuid.uuid4())
self.websockets[client_id] = websocket
# Send welcome message
await websocket.send_json({
"type": "welcome",
"client_id": client_id,
"timestamp": time.time()
})
try:
while True:
message = await websocket.receive_json()
msg_type = message.get("type")
if msg_type == "subscribe":
# Client wants to subscribe to agent events
agent_id = message.get("agent_id")
if agent_id and agent_id in self.agents:
# Send current agent info
await websocket.send_json({
"type": "agent_info",
"agent_id": agent_id,
"data": self.agents[agent_id].dict(),
"timestamp": time.time()
})
elif msg_type == "command":
# Client wants to send a command to an agent
agent_id = message.get("agent_id")
command = message.get("command")
data = message.get("data", {})
if agent_id and agent_id in self.agents and command:
# Publish command to agent's channel
await self.publish_event(f"agent:{agent_id}:commands", {
"command": command,
"data": data,
"sender": client_id,
"timestamp": time.time()
})
await websocket.send_json({
"type": "command_sent",
"agent_id": agent_id,
"command": command,
"timestamp": time.time()
})
except WebSocketDisconnect:
if client_id in self.websockets:
del self.websockets[client_id]
except Exception as e:
logger.error(f"WebSocket error: {e}")
if client_id in self.websockets:
del self.websockets[client_id]
async def start(self):
"""Start the agent process manager"""
# Setup signal handlers for graceful shutdown
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda: asyncio.create_task(self.shutdown()))
# Connect to Redis
await self.connect_redis()
# Start health check task
self._health_check_task = asyncio.create_task(self.health_check_loop())
# Start process monitoring task
self._monitor_task = asyncio.create_task(self.monitor_processes())
# Start FastAPI server
config = uvicorn.Config(
app=self.app,
host=self.host,
port=self.port,
log_level="info"
)
server = uvicorn.Server(config)
await server.serve()
async def connect_redis(self):
"""Connect to Redis for PubSub communication"""
try:
self.redis_client = await redis.from_url(self.redis_url)
await self.redis_client.ping()
logger.info("Connected to Redis successfully")
# Initialize PubSub
self.pubsub = self.redis_client.pubsub()
await self.pubsub.subscribe("agent_events")
# Start PubSub listener
self.pubsub_task = asyncio.create_task(self.pubsub_listener())
logger.info("Started PubSub listener")
return True
except Exception as e:
logger.error(f"Failed to connect to Redis: {e}")
return False
async def pubsub_listener(self):
"""Listen for PubSub messages from agents"""
try:
logger.info("PubSub listener started")
while not self._shutdown_event.is_set():
message = await self.pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0)
if message and message["type"] == "message":
channel = message["channel"]
if isinstance(channel, bytes):
channel = channel.decode('utf-8')
data = message["data"]
if isinstance(data, bytes):
data = data.decode('utf-8')
# Parse JSON data
try:
event_data = json.loads(data)
await self.handle_agent_event(channel, event_data)
except json.JSONDecodeError:
logger.error(f"Invalid JSON in message: {data}")
# Small sleep to prevent CPU spinning
await asyncio.sleep(0.01)
except asyncio.CancelledError:
logger.info("PubSub listener cancelled")
except Exception as e:
logger.error(f"Error in PubSub listener: {e}")
# Try to restart the listener if it fails
if not self._shutdown_event.is_set():
await asyncio.sleep(1)
self.pubsub_task = asyncio.create_task(self.pubsub_listener())
async def handle_agent_event(self, channel, event_data):
"""Handle events from agents"""
try:
event_type = event_data.get("type")
agent_id = event_data.get("agent_id")
if event_type == "heartbeat" and agent_id in self.agents:
# Update agent heartbeat
self.agents[agent_id].last_heartbeat = time.time()
self.agents[agent_id].status = "online"
# Update metrics if provided
if "memory_usage_mb" in event_data:
self.agents[agent_id].memory_usage_mb = event_data["memory_usage_mb"]
if "cpu_usage_percent" in event_data:
self.agents[agent_id].cpu_usage_percent = event_data["cpu_usage_percent"]
elif event_type == "agent_started" and agent_id in self.agents:
# Update agent status
self.agents[agent_id].status = "online"
self.agents[agent_id].pid = event_data.get("pid")
logger.info(f"Agent {agent_id} ({self.agents[agent_id].agent_name}) started")
# Forward event to WebSocket clients
await self.broadcast_agent_update(agent_id)
elif event_type == "agent_error" and agent_id in self.agents:
# Update agent status
self.agents[agent_id].status = "error"
self.agents[agent_id].health["error"] = event_data.get("error")
logger.error(f"Agent {agent_id} ({self.agents[agent_id].agent_name}) error: {event_data.get('error')}")
# Forward event to WebSocket clients
await self.broadcast_agent_update(agent_id)
elif event_type == "self_improvement" and agent_id in self.agents:
# Agent has self-improved
improvement = event_data.get("improvement", {})
logger.info(f"Agent {agent_id} ({self.agents[agent_id].agent_name}) self-improved: {improvement.get('description')}")
# Update agent capabilities if provided
if "new_capabilities" in improvement:
self.agents[agent_id].capabilities.extend(improvement["new_capabilities"])
# Forward event to WebSocket clients
await self.broadcast_event("agent_improved", {
"agent_id": agent_id,
"agent_name": self.agents[agent_id].agent_name,
"improvement": improvement
})
except Exception as e:
logger.error(f"Error handling agent event: {e}")
async def publish_event(self, channel, data):
"""Publish an event to Redis PubSub"""
try:
if not isinstance(data, dict):
data = {"data": data}
# Add timestamp if not present
if "timestamp" not in data:
data["timestamp"] = time.time()
await self.redis_client.publish(channel, json.dumps(data))
return True
except Exception as e:
logger.error(f"Failed to publish event to {channel}: {e}")
return False
async def broadcast_agent_update(self, agent_id):
"""Broadcast agent update to all WebSocket clients"""
if agent_id not in self.agents:
return
update = {
"type": "agent_update",
"agent_id": agent_id,
"data": self.agents[agent_id].dict(),
"timestamp": time.time()
}
# Send to all connected websockets
for ws in list(self.websockets.values()):
try:
await ws.send_json(update)
except Exception:
# Ignore errors, clients will be cleaned up on the next message
pass
async def broadcast_event(self, event_type, data):
"""Broadcast an event to all WebSocket clients"""
event = {
"type": event_type,
"data": data,
"timestamp": time.time()
}
# Send to all connected websockets
for ws in list(self.websockets.values()):
try:
await ws.send_json(event)
except Exception:
# Ignore errors, clients will be cleaned up on the next message
pass
async def start_agent_process(self, agent_config: AgentConfig):
"""Start an agent process"""
agent_id = agent_config.agent_id
try:
# Update agent status
if agent_id in self.agents:
self.agents[agent_id].status = "starting"
self.agents[agent_id].restart_count += 1
# Kill existing process if it exists
if agent_id in self.processes:
await self.stop_agent_process(agent_id)
# Create command to start agent
if agent_config.command:
cmd = agent_config.command
else:
# Default command for different agent types
if agent_config.agent_type == "cli":
cmd = [
sys.executable, "-m", "cli_agent",
"--port", str(agent_config.port),
"--agent-id", agent_id,
"--agent-name", agent_config.agent_name,
"--model", agent_config.model
]
elif agent_config.agent_type == "web":
cmd = [
sys.executable, "-m", "web_app",
"--port", str(agent_config.port),
"--agent-id", agent_id,
"--agent-name", agent_config.agent_name,
"--model", agent_config.model
]
else:
# Generic agent
cmd = [
sys.executable, "-m", f"{agent_config.agent_type}_agent",
"--port", str(agent_config.port),
"--agent-id", agent_id,
"--agent-name", agent_config.agent_name,
"--model", agent_config.model
]
# Prepare environment variables
env = os.environ.copy()
env["REDIS_URL"] = self.redis_url
env["AGENT_ID"] = agent_id
env["AGENT_NAME"] = agent_config.agent_name
env["AGENT_TYPE"] = agent_config.agent_type
env["AGENT_PORT"] = str(agent_config.port)
# Add custom environment variables
for key, value in agent_config.env_vars.items():
env[key] = value
# Start the process
logger.info(f"Starting agent process {agent_id} ({agent_config.agent_name}): {cmd}")
process = subprocess.Popen(
cmd,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1
)
self.processes[agent_id] = process
# Start background tasks to handle stdout/stderr
asyncio.create_task(self.process_output(agent_id, process.stdout, "stdout"))
asyncio.create_task(self.process_output(agent_id, process.stderr, "stderr"))
# Wait for agent to start (check health endpoint)
start_time = time.time()
started = False
while time.time() - start_time < agent_config.startup_timeout:
# Check if process has exited
if process.poll() is not None:
logger.error(f"Agent process {agent_id} exited prematurely with code {process.returncode}")
if agent_id in self.agents:
self.agents[agent_id].status = "error"
self.agents[agent_id].health["error"] = f"Process exited with code {process.returncode}"
# Try to restart if configured
if agent_config.auto_restart and self.agents[agent_id].restart_count < agent_config.max_restart_attempts:
logger.info(f"Restarting agent {agent_id} (attempt {self.agents[agent_id].restart_count + 1})")
await asyncio.sleep(agent_config.restart_delay)
await self.start_agent_process(agent_config)
break
# Wait a bit before checking
await asyncio.sleep(1)
# Update PID in agent info
if agent_id in self.agents:
self.agents[agent_id].pid = process.pid
# Call health endpoint to check if agent is up
try:
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get(f"http://{agent_config.host}:{agent_config.port}/health", timeout=2) as response:
if response.status == 200:
started = True
logger.info(f"Agent {agent_id} ({agent_config.agent_name}) started successfully")
if agent_id in self.agents:
self.agents[agent_id].status = "online"
self.agents[agent_id].last_heartbeat = time.time()
break
except Exception:
# Keep trying until timeout
pass
if not started:
logger.error(f"Agent {agent_id} failed to start within timeout period")
if agent_id in self.agents:
self.agents[agent_id].status = "error"
self.agents[agent_id].health["error"] = "Failed to start within timeout period"
# Try to restart if configured
if agent_config.auto_restart and self.agents[agent_id].restart_count < agent_config.max_restart_attempts:
logger.info(f"Restarting agent {agent_id} (attempt {self.agents[agent_id].restart_count + 1})")
await asyncio.sleep(agent_config.restart_delay)
await self.start_agent_process(agent_config)
# Broadcast agent update
await self.broadcast_agent_update(agent_id)
# Publish agent started event
await self.publish_event("agent_events", {
"type": "agent_started",
"agent_id": agent_id,
"agent_name": agent_config.agent_name,
"agent_type": agent_config.agent_type,
"pid": process.pid,
"port": agent_config.port
})
except Exception as e:
logger.error(f"Error starting agent process {agent_id}: {e}")
if agent_id in self.agents:
self.agents[agent_id].status = "error"
self.agents[agent_id].health["error"] = str(e)
# Try to restart if configured
if agent_config.auto_restart and agent_id in self.agents and self.agents[agent_id].restart_count < agent_config.max_restart_attempts:
logger.info(f"Restarting agent {agent_id} (attempt {self.agents[agent_id].restart_count + 1})")
await asyncio.sleep(agent_config.restart_delay)
await self.start_agent_process(agent_config)
async def stop_agent_process(self, agent_id):
"""Stop an agent process"""
if agent_id not in self.processes:
return
process = self.processes[agent_id]
logger.info(f"Stopping agent process {agent_id}")
try:
# Try graceful shutdown first
process.terminate()
# Wait a bit for process to terminate
for _ in range(5):
if process.poll() is not None:
break
await asyncio.sleep(1)
# Force kill if still running
if process.poll() is None:
process.kill()
await asyncio.sleep(1)
# Update agent status
if agent_id in self.agents:
self.agents[agent_id].status = "stopped"
self.agents[agent_id].pid = None
# Remove from processes dict
del self.processes[agent_id]
# Broadcast agent update
await self.broadcast_agent_update(agent_id)
logger.info(f"Agent process {agent_id} stopped")
return True
except Exception as e:
logger.error(f"Error stopping agent process {agent_id}: {e}")
return False
async def process_output(self, agent_id, pipe, pipe_name):
"""Process stdout/stderr from agent process"""
try:
for line in iter(pipe.readline, ''):
if not line:
break
# Log output with agent ID
if pipe_name == "stderr":
logger.error(f"[Agent {agent_id}] {line.strip()}")
else:
logger.info(f"[Agent {agent_id}] {line.strip()}")
except Exception as e:
logger.error(f"Error processing {pipe_name} for agent {agent_id}: {e}")
finally:
pipe.close()
async def health_check_loop(self):
"""Periodically check health of all agents"""
try:
while not self._shutdown_event.is_set():
current_time = time.time()
for agent_id, agent in list(self.agents.items()):
# Check if agent has timed out (no heartbeat for 60 seconds)
if agent.status == "online" and current_time - agent.last_heartbeat > 60:
logger.warning(f"Agent {agent_id} ({agent.agent_name}) heartbeat timeout")
agent.status = "timeout"
# Try to restart if process exists
if agent_id in self.processes:
process = self.processes[agent_id]
# Check if process is still running
if process.poll() is None:
# Process is running but not responding, restart it
logger.info(f"Restarting agent {agent_id} due to heartbeat timeout")
agent_config = AgentConfig(
agent_id=agent.agent_id,
agent_name=agent.agent_name,
agent_type=agent.agent_type,
host=agent.host,
port=agent.port,
capabilities=agent.capabilities
)
asyncio.create_task(self.start_agent_process(agent_config))
# Broadcast agent update
await self.broadcast_agent_update(agent_id)
# Wait before next check
await asyncio.sleep(10)
except asyncio.CancelledError:
logger.info("Health check loop cancelled")
except Exception as e:
logger.error(f"Error in health check loop: {e}")
# Restart the health check loop if it fails
if not self._shutdown_event.is_set():
await asyncio.sleep(1)
self._health_check_task = asyncio.create_task(self.health_check_loop())
async def monitor_processes(self):
"""Monitor resource usage of agent processes"""
try:
while not self._shutdown_event.is_set():
# Check each process
for agent_id, agent in list(self.agents.items()):
if agent.pid and agent.status == "online":
try:
# Get process info
process = psutil.Process(agent.pid)
# Get memory usage (MB)
memory_info = process.memory_info()
memory_mb = memory_info.rss / (1024 * 1024)
agent.memory_usage_mb = memory_mb
# Get CPU usage
cpu_percent = process.cpu_percent(interval=0.1)
agent.cpu_usage_percent = cpu_percent
# Check resource limits
if hasattr(agent, "memory_limit_mb") and agent.memory_limit_mb and memory_mb > agent.memory_limit_mb:
logger.warning(f"Agent {agent_id} exceeded memory limit: {memory_mb:.2f}MB > {agent.memory_limit_mb}MB")
# Restart the agent
logger.info(f"Restarting agent {agent_id} due to memory limit exceeded")
agent_config = AgentConfig(
agent_id=agent.agent_id,
agent_name=agent.agent_name,
agent_type=agent.agent_type,
host=agent.host,
port=agent.port,
capabilities=agent.capabilities,
memory_limit_mb=agent.memory_limit_mb
)
asyncio.create_task(self.start_agent_process(agent_config))
if hasattr(agent, "cpu_limit_percent") and agent.cpu_limit_percent and cpu_percent > agent.cpu_limit_percent:
logger.warning(f"Agent {agent_id} exceeded CPU limit: {cpu_percent:.2f}% > {agent.cpu_limit_percent}%")
# Slow down the agent by reducing its priority
try:
process.nice(10) # Lower priority
except Exception:
pass
except psutil.NoSuchProcess:
# Process no longer exists
if agent.status == "online":
logger.warning(f"Agent process {agent_id} ({agent.agent_name}) not found, marking as crashed")
agent.status = "crashed"
agent.pid = None
# Broadcast agent update
await self.broadcast_agent_update(agent_id)
except Exception as e:
logger.error(f"Error monitoring agent {agent_id}: {e}")
# Wait before next check
await asyncio.sleep(5)
except asyncio.CancelledError:
logger.info("Process monitor cancelled")
except Exception as e:
logger.error(f"Error in process monitor: {e}")
# Restart the monitor task if it fails
if not self._shutdown_event.is_set():
await asyncio.sleep(1)
self._monitor_task = asyncio.create_task(self.monitor_processes())
async def shutdown(self):
"""Shutdown the agent process manager"""
logger.info("Shutting down Agent Process Manager...")
# Signal shutdown
self._shutdown_event.set()
# Stop all agent processes
for agent_id in list(self.processes.keys()):
await self.stop_agent_process(agent_id)
# Cancel background tasks
if self.pubsub_task:
self.pubsub_task.cancel()
try:
await self.pubsub_task
except asyncio.CancelledError:
pass
if self._health_check_task:
self._health_check_task.cancel()
try:
await self._health_check_task
except asyncio.CancelledError:
pass
if self._monitor_task:
self._monitor_task.cancel()
try:
await self._monitor_task
except asyncio.CancelledError:
pass
# Close Redis connection
if self.pubsub:
await self.pubsub.unsubscribe()
if self.redis_client:
await self.redis_client.close()
# Close all WebSocket connections
for ws in list(self.websockets.values()):
try:
await ws.close()
except Exception:
pass
logger.info("Agent Process Manager shutdown complete")
class AgentServer:
"""Base class for agent servers with FastAPI and Redis PubSub integration"""
def __init__(self, agent_id=None, agent_name=None, agent_type=None,
host="127.0.0.1", port=8600, redis_url=None, model="gpt-4"):
self.agent_id = agent_id or f"agent-{uuid.uuid4().hex[:8]}"
self.agent_name = agent_name or f"Agent-{self.agent_id[:4]}"
self.agent_type = agent_type or "generic"
self.host = host
self.port = port
self.redis_url = redis_url or os.getenv("REDIS_URL", "redis://localhost:6379/0")
self.model = model
self.capabilities = []
self.redis_client = None
self.pubsub = None
self.pubsub_task = None
self.app = FastAPI(title=f"{self.agent_name} API")
self.setup_api()
self._shutdown_event = asyncio.Event()
self._heartbeat_task = None
logger.info(f"Agent {self.agent_id} ({self.agent_name}) initialized on {host}:{port} with Redis URL: {self.redis_url}")
def setup_api(self):
"""Setup FastAPI routes and CORS middleware"""
# Add CORS middleware
self.app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# API routes
@self.app.get("/")
async def root():
return {
"agent_id": self.agent_id,
"agent_name": self.agent_name,
"agent_type": self.agent_type,
"status": "online"
}
@self.app.get("/health")
async def health_check():
return {
"status": "healthy",
"agent_id": self.agent_id,
"agent_name": self.agent_name,
"timestamp": time.time(),
"uptime": time.time() - self.start_time,
"redis_connected": self.redis_client is not None
}
@self.app.get("/capabilities")
async def get_capabilities():
return {"capabilities": self.capabilities}
async def start(self):
"""Start the agent server"""
self.start_time = time.time()
# Setup signal handlers for graceful shutdown
loop = asyncio.get_running_loop()
for sig in (signal.SIGINT, signal.SIGTERM):
loop.add_signal_handler(sig, lambda: asyncio.create_task(self.shutdown()))
# Connect to Redis
await self.connect_redis()
# Start heartbeat task
self._heartbeat_task = asyncio.create_task(self.heartbeat_loop())
# Publish agent started event
await self.publish_event("agent_events", {
"type": "agent_started",
"agent_id": self.agent_id,
"agent_name": self.agent_name,
"agent_type": self.agent_type,
"pid": os.getpid(),
"port": self.port
})
# Start FastAPI server
config = uvicorn.Config(
app=self.app,
host=self.host,
port=self.port,
log_level="info"
)
server = uvicorn.Server(config)
await server.serve()
async def connect_redis(self):
"""Connect to Redis for PubSub communication"""
try:
self.redis_client = await redis.from_url(self.redis_url)
await self.redis_client.ping()
logger.info(f"Agent {self.agent_id} connected to Redis successfully")
# Initialize PubSub
self.pubsub = self.redis_client.pubsub()
# Subscribe to agent-specific channels
await self.pubsub.subscribe(f"agent:{self.agent_id}:commands")
# Start PubSub listener
self.pubsub_task = asyncio.create_task(self.pubsub_listener())
logger.info(f"Agent {self.agent_id} started PubSub listener")
return True
except Exception as e:
logger.error(f"Agent {self.agent_id} failed to connect to Redis: {e}")
return False
async def pubsub_listener(self):
"""Listen for PubSub messages"""
try:
logger.info(f"Agent {self.agent_id} PubSub listener started")
while not self._shutdown_event.is_set():
message = await self.pubsub.get_message(ignore_subscribe_messages=True, timeout=1.0)
if message and message["type"] == "message":
channel = message["channel"]
if isinstance(channel, bytes):
channel = channel.decode('utf-8')
data = message["data"]
if isinstance(data, bytes):
data = data.decode('utf-8')
# Parse JSON data
try:
command_data = json.loads(data)
await self.handle_command(channel, command_data)
except json.JSONDecodeError:
logger.error(f"Agent {self.agent_id} received invalid JSON in message: {data}")
# Small sleep to prevent CPU spinning
await asyncio.sleep(0.01)
except asyncio.CancelledError:
logger.info(f"Agent {self.agent_id} PubSub listener cancelled")
except Exception as e:
logger.error(f"Error in Agent {self.agent_id} PubSub listener: {e}")
# Try to restart the listener if it fails
if not self._shutdown_event.is_set():
await asyncio.sleep(1)
self.pubsub_task = asyncio.create_task(self.pubsub_listener())
async def handle_command(self, channel, command_data):
"""Handle commands from PubSub"""
try:
command = command_data.get("command")
data = command_data.get("data", {})
sender = command_data.get("sender")
logger.info(f"Agent {self.agent_id} received command: {command} from {sender}")
# Handle different commands
if command == "ping":
# Respond to ping
await self.publish_event(f"agent:{self.agent_id}:responses", {
"type": "pong",
"agent_id": self.agent_id,
"receiver": sender,
"timestamp": time.time()
})
elif command == "shutdown":
# Shutdown the agent
logger.info(f"Agent {self.agent_id} received shutdown command from {sender}")
await self.shutdown()
elif command == "update_capabilities":
# Update capabilities
if "capabilities" in data:
self.capabilities = data["capabilities"]
logger.info(f"Agent {self.agent_id} updated capabilities: {self.capabilities}")
# Publish capabilities updated event
await self.publish_event("agent_events", {
"type": "capabilities_updated",
"agent_id": self.agent_id,
"capabilities": self.capabilities
})
else:
# Override in subclasses to handle specific commands
await self.process_command(command, data, sender)
except Exception as e:
logger.error(f"Error handling command in Agent {self.agent_id}: {e}")
async def process_command(self, command, data, sender):
"""Process custom commands - override in subclasses"""
# Handle standard capability discovery
if command == "get_capabilities":
# Send capabilities information
await self.publish_event(f"agent:{self.agent_id}:responses", {
"type": "capabilities",