omgy commited on
Commit
bb1a847
Β·
verified Β·
1 Parent(s): 3339f3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -52
app.py CHANGED
@@ -4,101 +4,84 @@ import requests
4
  from fastapi import FastAPI
5
  from fastapi.middleware.cors import CORSMiddleware
6
 
7
- # ============ CONFIG ============
8
  BACKEND_URL = "https://careflownexus-production.up.railway.app"
9
- AGENT_ROLE = os.getenv("AGENT_ROLE", "CLEANER").upper() # MASTER/BED/CLEANER/NURSE
10
- POLL_INTERVAL = 3 # seconds
11
 
12
- app = FastAPI(title=f"{AGENT_ROLE} Agent Service")
 
 
 
 
 
 
 
13
 
14
- # CORS
15
  app.add_middleware(
16
  CORSMiddleware,
17
  allow_origins=["*"],
18
- allow_credentials=True,
19
  allow_methods=["*"],
20
  allow_headers=["*"],
 
21
  )
22
 
23
- # Status
24
  @app.get("/")
25
  def status():
26
- return {
27
- "agent_role": AGENT_ROLE,
28
- "polling": True,
29
- "backend": BACKEND_URL
30
- }
31
 
32
- # ============ AGENT LOGIC ============
33
 
34
  def poll_tasks():
35
- """Fetch pending tasks for this agent."""
36
  try:
37
  url = f"{BACKEND_URL}/agent/tasks?role={AGENT_ROLE}"
38
- response = requests.get(url)
39
- response.raise_for_status()
40
- tasks = response.json()
41
- return tasks if isinstance(tasks, list) else []
42
  except Exception as e:
43
- print("Error polling tasks:", e)
44
  return []
45
 
 
46
  def complete_task(task):
47
- """Complete the task using the proper backend endpoint."""
48
  try:
49
  task_id = task["id"]
50
  task_type = task["type"]
51
  payload = {}
52
 
53
- # ==== BED agent must choose a bed ====
54
  if AGENT_ROLE == "BED" and task_type == "bed_assignment":
55
- available = task.get("context", {}).get("available_beds", [])
56
- if not available:
57
- print("No available beds!")
58
  return
59
-
60
- chosen_bed = available[0]["id"]
61
- payload = {"bed_id": chosen_bed}
62
-
63
- # CLEANER (cleaning / post_discharge_cleaning)
64
- if AGENT_ROLE == "CLEANER":
65
- payload = {}
66
-
67
- # NURSE (nurse_assignment or discharge_work)
68
- if AGENT_ROLE == "NURSE":
69
- payload = {}
70
 
71
  url = f"{BACKEND_URL}/agent/tasks/{task_id}/complete"
72
- response = requests.post(url, json=payload)
73
- response.raise_for_status()
74
 
75
- print(f"βœ” Completed task {task_id}: {task_type}")
76
- print(response.json())
77
 
78
  except Exception as e:
79
- print("Error completing task:", e)
80
-
81
 
82
- # Background polling task
83
- def run_agent_loop():
84
- print(f"Starting {AGENT_ROLE} agent loop...")
85
 
 
 
86
  while True:
87
  tasks = poll_tasks()
88
 
89
  if tasks:
90
- print(f"πŸ”” {len(tasks)} task(s) available")
91
- for task in tasks:
92
- complete_task(task)
93
  else:
94
- print("No tasks available.")
95
 
96
  time.sleep(POLL_INTERVAL)
97
 
98
 
99
- # Startup event
100
  @app.on_event("startup")
101
- def start_background_task():
102
  import threading
103
- thread = threading.Thread(target=run_agent_loop, daemon=True)
104
- thread.start()
 
4
  from fastapi import FastAPI
5
  from fastapi.middleware.cors import CORSMiddleware
6
 
 
7
  BACKEND_URL = "https://careflownexus-production.up.railway.app"
8
+ AGENT_ROLE = os.getenv("AGENT_ROLE", "CLEANER").upper()
 
9
 
10
+ POLL_INTERVAL = 4
11
+
12
+ HEADERS = {
13
+ "User-Agent": f"{AGENT_ROLE}-agent",
14
+ "Accept": "application/json"
15
+ }
16
+
17
+ app = FastAPI(title=f"{AGENT_ROLE} Agent")
18
 
 
19
  app.add_middleware(
20
  CORSMiddleware,
21
  allow_origins=["*"],
 
22
  allow_methods=["*"],
23
  allow_headers=["*"],
24
+ allow_credentials=True,
25
  )
26
 
27
+
28
  @app.get("/")
29
  def status():
30
+ return {"status": "running", "agent": AGENT_ROLE, "backend": BACKEND_URL}
 
 
 
 
31
 
 
32
 
33
  def poll_tasks():
 
34
  try:
35
  url = f"{BACKEND_URL}/agent/tasks?role={AGENT_ROLE}"
36
+ res = requests.get(url, headers=HEADERS)
37
+ res.raise_for_status()
38
+ data = res.json()
39
+ return data if isinstance(data, list) else []
40
  except Exception as e:
41
+ print("❌ Error polling tasks:", e)
42
  return []
43
 
44
+
45
  def complete_task(task):
 
46
  try:
47
  task_id = task["id"]
48
  task_type = task["type"]
49
  payload = {}
50
 
 
51
  if AGENT_ROLE == "BED" and task_type == "bed_assignment":
52
+ beds = task.get("context", {}).get("available_beds", [])
53
+ if not beds:
54
+ print("No beds available")
55
  return
56
+ payload = {"bed_id": beds[0]["id"]}
 
 
 
 
 
 
 
 
 
 
57
 
58
  url = f"{BACKEND_URL}/agent/tasks/{task_id}/complete"
59
+ res = requests.post(url, json=payload, headers=HEADERS)
60
+ res.raise_for_status()
61
 
62
+ print(f"βœ” Completed {task_id}: {task_type}")
 
63
 
64
  except Exception as e:
65
+ print("❌ Error completing task:", e)
 
66
 
 
 
 
67
 
68
+ def run_loop():
69
+ print(f"πŸ”„ {AGENT_ROLE} agent started...")
70
  while True:
71
  tasks = poll_tasks()
72
 
73
  if tasks:
74
+ print("πŸ”” Tasks:", tasks)
75
+ for t in tasks:
76
+ complete_task(t)
77
  else:
78
+ print("No tasks.")
79
 
80
  time.sleep(POLL_INTERVAL)
81
 
82
 
 
83
  @app.on_event("startup")
84
+ def start_loop():
85
  import threading
86
+ time.sleep(2) # HF boot delay fix
87
+ threading.Thread(target=run_loop, daemon=True).start()