File size: 15,112 Bytes
069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a e5eefbc 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 069c35a 250e5f3 | 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 | import os
import json
import httpx
from dotenv import load_dotenv
from supabase import create_client
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
supabase = None
if all([GROQ_API_KEY, SUPABASE_URL, SUPABASE_KEY]):
try:
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
except Exception as e:
print(f"WARNING: Could not initialize Supabase: {e}")
# βββββββββββββββββββββββββββββββββββββββββ
# TOOL FUNCTIONS
# βββββββββββββββββββββββββββββββββββββββββ
def get_patient_by_name(name: str):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("patients").select("*").ilike("name", f"%{name}%").execute()
return res.data if res.data else {"error": "Patient not found"}
def get_patients_by_doctor(doctor: str):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("patients").select("*").ilike("doctor", f"%{doctor}%").execute()
return res.data if res.data else {"error": "No patients found for this doctor"}
def get_admitted_patients():
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("patients").select("*").eq("status", "admitted").execute()
return res.data if res.data else {"message": "No admitted patients currently"}
def get_appointments_by_date(date: str):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("appointments").select("*").eq("date", date).execute()
return res.data if res.data else {"message": f"No appointments on {date}"}
def get_patient_appointments(patient_name: str):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("appointments").select("*").ilike("patient_name", f"%{patient_name}%").execute()
return res.data if res.data else {"error": "No appointments found for this patient"}
def add_patient(name: str, age: int, gender: str, disease: str, doctor: str, admission_date: str):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
data = {
"name": name,
"age": age,
"gender": gender,
"disease": disease,
"doctor": doctor,
"admission_date": admission_date,
"status": "admitted"
}
res = supabase.table("patients").insert(data).execute()
return {"success": True, "patient": res.data[0]} if res.data else {"error": "Failed to add patient"}
def discharge_patient(patient_id: int):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("patients").update({"status": "discharged"}).eq("id", patient_id).execute()
return {"success": True, "message": f"Patient {patient_id} discharged"} if res.data else {"error": "Patient not found"}
def update_appointment_status(appointment_id: int, status: str):
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
if status not in ["scheduled", "completed", "cancelled"]:
return {"error": "Invalid status. Use: scheduled, completed, cancelled"}
res = supabase.table("appointments").update({"status": status}).eq("id", appointment_id).execute()
return {"success": True, "message": f"Appointment {appointment_id} updated to {status}"} if res.data else {"error": "Appointment not found"}
def get_disease_statistics():
if not supabase:
return {"error": "Database not connected. Check SUPABASE_URL and SUPABASE_KEY."}
res = supabase.table("patients").select("disease").execute()
if not res.data:
return {"message": "No data available"}
stats = {}
for row in res.data:
d = row["disease"]
stats[d] = stats.get(d, 0) + 1
return stats
# βββββββββββββββββββββββββββββββββββββββββ
# FUNCTION MAP
# βββββββββββββββββββββββββββββββββββββββββ
available_functions = {
"get_patient_by_name": get_patient_by_name,
"get_patients_by_doctor": get_patients_by_doctor,
"get_admitted_patients": get_admitted_patients,
"get_appointments_by_date": get_appointments_by_date,
"get_patient_appointments": get_patient_appointments,
"add_patient": add_patient,
"discharge_patient": discharge_patient,
"update_appointment_status": update_appointment_status,
"get_disease_statistics": get_disease_statistics,
}
# βββββββββββββββββββββββββββββββββββββββββ
# TOOLS SCHEMA
# βββββββββββββββββββββββββββββββββββββββββ
tools = [
{
"type": "function",
"function": {
"name": "get_patient_by_name",
"description": "Search and get patient details by name",
"parameters": {
"type": "object",
"properties": {"name": {"type": "string"}},
"required": ["name"]
}
}
},
{
"type": "function",
"function": {
"name": "get_patients_by_doctor",
"description": "Get all patients assigned to a specific doctor",
"parameters": {
"type": "object",
"properties": {"doctor": {"type": "string"}},
"required": ["doctor"]
}
}
},
{
"type": "function",
"function": {
"name": "get_admitted_patients",
"description": "Get all currently admitted patients",
"parameters": {"type": "object", "properties": {}}
}
},
{
"type": "function",
"function": {
"name": "get_appointments_by_date",
"description": "Get all appointments on a specific date (format: YYYY-MM-DD)",
"parameters": {
"type": "object",
"properties": {"date": {"type": "string"}},
"required": ["date"]
}
}
},
{
"type": "function",
"function": {
"name": "get_patient_appointments",
"description": "Get all appointments for a specific patient by name",
"parameters": {
"type": "object",
"properties": {"patient_name": {"type": "string"}},
"required": ["patient_name"]
}
}
},
{
"type": "function",
"function": {
"name": "add_patient",
"description": "Register a new patient in the hospital system",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"gender": {"type": "string"},
"disease": {"type": "string"},
"doctor": {"type": "string"},
"admission_date": {"type": "string", "description": "Format: YYYY-MM-DD"}
},
"required": ["name", "age", "gender", "disease", "doctor", "admission_date"]
}
}
},
{
"type": "function",
"function": {
"name": "discharge_patient",
"description": "Discharge a patient by their ID (change status to discharged)",
"parameters": {
"type": "object",
"properties": {"patient_id": {"type": "integer"}},
"required": ["patient_id"]
}
}
},
{
"type": "function",
"function": {
"name": "update_appointment_status",
"description": "Update the status of an appointment (scheduled, completed, or cancelled)",
"parameters": {
"type": "object",
"properties": {
"appointment_id": {"type": "integer"},
"status": {"type": "string", "enum": ["scheduled", "completed", "cancelled"]}
},
"required": ["appointment_id", "status"]
}
}
},
{
"type": "function",
"function": {
"name": "get_disease_statistics",
"description": "Get count of patients grouped by disease/condition",
"parameters": {"type": "object", "properties": {}}
}
}
]
# βββββββββββββββββββββββββββββββββββββββββ
# MAIN AGENT
# βββββββββββββββββββββββββββββββββββββββββ
SYSTEM_PROMPT = """You are MedBot, a hospital admin assistant for City General Hospital.
ABSOLUTE RULES - NEVER BREAK THESE:
1. YOU MUST ALWAYS RESPOND IN ENGLISH ONLY. This is mandatory. Never use Hindi, Urdu, Hinglish, or any other language. Not even one word in another language.
2. You are ONLY a hospital admin assistant. Reject all non-hospital queries politely in English.
You help admins with:
- Patient records (search, add, discharge)
- Doctor-patient assignments
- Appointment management
- Disease statistics
Always use available tools for database queries.
Format responses cleanly with bullet points for multiple records.
"""
async def process_agent_chat(user_message: str):
try:
if not GROQ_API_KEY:
return {"response": "Error: GROQ_API_KEY not configured. Please set it in Space Variables."}
headers = {
"Authorization": f"Bearer {GROQ_API_KEY}",
"Content-Type": "application/json"
}
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message}
]
payload = {
"model": "llama-3.3-70b-versatile",
"messages": messages,
"tools": tools,
"tool_choice": "auto",
"temperature": 0.2
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(
"https://api.groq.com/openai/v1/chat/completions",
headers=headers,
json=payload
)
# Handle non-200 responses from Groq (e.g. invalid key, rate limit)
if response.status_code != 200:
try:
error_data = response.json()
error_msg = error_data.get("error", {}).get("message", response.text)
except Exception:
error_msg = response.text
return {"response": f"β οΈ Groq API Error (Status {response.status_code}): {error_msg}"}
try:
data = response.json()
except Exception as e:
return {"response": f"β οΈ Failed to parse Groq response as JSON. Status code: {response.status_code}. Raw response: {response.text}"}
print("GROQ RESPONSE:", data)
if "choices" not in data or not data["choices"]:
return {"response": f"β οΈ Error: Groq response did not contain 'choices'. Full response: {data}"}
assistant_message = data["choices"][0]["message"]
tool_calls = assistant_message.get("tool_calls")
if not tool_calls:
return {"response": assistant_message.get("content", "No response text received.")}
messages.append(assistant_message)
for tool_call in tool_calls:
function_name = tool_call["function"]["name"]
function_args = tool_call["function"].get("arguments")
try:
function_args = json.loads(function_args) if function_args else {}
except Exception as e:
function_args = {}
print(f"Error parsing tool arguments: {e}")
if function_name not in available_functions:
function_response = {"error": f"Function '{function_name}' is not supported."}
else:
function_to_call = available_functions[function_name]
try:
try:
function_response = function_to_call(**function_args)
except TypeError:
function_response = function_to_call()
except Exception as e:
import traceback
print(f"Error executing database tool '{function_name}': {e}")
traceback.print_exc()
function_response = {"error": f"Database query failed in {function_name}: {str(e)}"}
messages.append({
"role": "tool",
"tool_call_id": tool_call["id"],
"name": function_name,
"content": json.dumps(function_response)
})
second_payload = {
"model": "llama-3.3-70b-versatile",
"messages": messages,
"temperature": 0.2
}
async with httpx.AsyncClient(timeout=30.0) as client:
final_response = await client.post(
"https://api.groq.com/openai/v1/chat/completions",
headers=headers,
json=second_payload
)
if final_response.status_code != 200:
try:
error_data = final_response.json()
error_msg = error_data.get("error", {}).get("message", final_response.text)
except Exception:
error_msg = final_response.text
return {"response": f"β οΈ Groq Final Response Generation Error (Status {final_response.status_code}): {error_msg}"}
try:
final_data = final_response.json()
except Exception as e:
return {"response": f"β οΈ Failed to parse Groq final response as JSON. Status code: {final_response.status_code}. Raw response: {final_response.text}"}
if "choices" not in final_data or not final_data["choices"]:
return {"response": f"β οΈ Error: Groq final response did not contain 'choices'. Full response: {final_data}"}
final_answer = final_data["choices"][0]["message"].get("content", "No final answer generated.")
return {"response": final_answer}
except Exception as e:
import traceback
error_trace = traceback.format_exc()
print("RUNTIME ERROR IN process_agent_chat:\n", error_trace)
return {"response": f"β οΈ Server Runtime Error: {str(e)}\n\nTraceback:\n{error_trace}"} |