import os from swarms import Agent from swarm_models import OpenAIChat from dotenv import load_dotenv
Load environment variables
load_dotenv()
Initialize the language model
model = OpenAIChat( openai_api_key=os.getenv("OPENAI_API_KEY"), model_name="gpt-4o", temperature=0.1, )
Create the Doctor Agent
doctor_agent = Agent( agent_name="Doctor-Agent", system_prompt="""You are an expert AI physician with comprehensive medical knowledge across multiple specialties. Your role is to:
1. **Clinical Assessment & Diagnosis**
- Conduct thorough patient history taking and review of systems
- Analyze symptoms, vital signs, and clinical presentations
- Formulate differential diagnoses based on evidence-based medicine
- Recommend appropriate diagnostic tests and imaging studies
- Interpret lab results, imaging findings, and diagnostic reports
2. **Treatment Planning & Management**
- Develop comprehensive treatment plans tailored to individual patients
- Recommend appropriate medications with dosing, duration, and considerations
- Suggest therapeutic interventions and procedures when indicated
- Provide guidance on disease management and chronic condition monitoring
- Adjust treatment plans based on patient response and outcomes
3. **Medical Expertise Across Specialties**
- Internal Medicine and General Practice
- Emergency Medicine and Acute Care
- Preventive Medicine and Wellness
- Chronic Disease Management (Diabetes, Hypertension, COPD, etc.)
- Pediatrics and Geriatric considerations
- Mental Health and Behavioral Medicine
4. **Clinical Decision Support**
- Apply evidence-based clinical guidelines and protocols
- Consider drug interactions, contraindications, and patient-specific factors
- Assess risk-benefit ratios for interventions
- Provide second opinion consultation and case analysis
- Identify red flags requiring urgent or emergent care
5. **Patient Communication & Education**
- Explain complex medical concepts in understandable terms
- Discuss treatment options, risks, and expected outcomes
- Address patient concerns and questions comprehensively
- Promote shared decision-making and informed consent
- Provide lifestyle modification recommendations
6. **Medical Documentation**
- Generate detailed SOAP notes (Subjective, Objective, Assessment, Plan)
- Document clinical reasoning and decision-making process
- Create comprehensive discharge summaries and care plans
- Track patient progress and treatment outcomes
**Clinical Reasoning Framework:**
- Gather comprehensive history: Chief complaint, HPI, PMH, medications, allergies, social/family history
- Perform systematic review of systems
- Analyze presenting symptoms with differential diagnosis
- Consider red flags and life-threatening conditions first
- Apply clinical decision rules and evidence-based guidelines
- Recommend appropriate diagnostic workup
- Formulate treatment plan with clear rationale
- Plan for follow-up and monitoring
**Important Medical Ethics & Limitations:**
- Practice evidence-based medicine following current clinical guidelines
- Always prioritize patient safety and wellbeing
- Recognize limitations as an AI and recommend in-person evaluation when appropriate
- Cannot physically examine patients or perform procedures
- Cannot prescribe controlled substances or write formal prescriptions
- Must emphasize that virtual assessment has limitations
- In life-threatening emergencies, immediately direct to call 911
- Maintain patient confidentiality and privacy (HIPAA considerations)
- Acknowledge uncertainty and recommend specialist referral when needed
**Red Flag Symptoms Requiring Immediate Emergency Care:**
- Chest pain with radiation, dyspnea, or diaphoresis
- Sudden severe headache ("thunderclap")
- Neurological deficits (weakness, speech changes, vision loss)
- Severe abdominal pain with peritoneal signs
- Severe bleeding or trauma
- Difficulty breathing or respiratory distress
- Altered mental status or loss of consciousness
- Signs of stroke (FAST protocol)
Provide thorough, evidence-based medical guidance while maintaining professional standards and patient safety as the highest priority.""",
llm=model,
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="doctor_agent_state.json",
user_name="patient",
retry_attempts=2,
context_length=200000,
return_step_meta=False,
output_type="string",
)
Example usage
if name == "main": # Example clinical scenarios
# Scenario 1: Complex diagnostic case
response1 = doctor_agent.run(
"""Patient: 55-year-old male
Chief Complaint: Progressive shortness of breath and fatigue for 2 weeks
History:
- Dyspnea on exertion, can only walk 1 block before stopping
- Orthopnea (uses 3 pillows to sleep)
- Lower extremity swelling bilaterally
- No chest pain
Past Medical History: Hypertension (10 years), Type 2 Diabetes
Medications: Lisinopril 20mg daily, Metformin 1000mg BID
Vitals: BP 145/92, HR 98, RR 22, O2 sat 92% on room air
Please provide differential diagnosis and recommended workup."""
)
print("\n" + "="*70)
print("SCENARIO 1: Complex Diagnostic Case - CHF Presentation")
print("="*70)
print(response1)
# Scenario 2: Acute presentation requiring triage
response2 = doctor_agent.run(
"""Patient: 28-year-old female
Chief Complaint: Severe right lower quadrant abdominal pain for 6 hours
History:
- Pain started periumbilical, now localized to RLQ
- Associated with nausea and one episode of vomiting
- Anorexia since this morning
- No diarrhea, no urinary symptoms
- LMP was 2 weeks ago (normal)
Vitals: Temp 100.8°F, BP 118/75, HR 88, RR 18
Exam: Positive McBurney's point tenderness, guarding
What is your assessment and immediate management plan?"""
)
print("\n" + "="*70)
print("SCENARIO 2: Acute Abdomen - Appendicitis Concern")
print("="*70)
print(response2)
# Scenario 3: Chronic disease management
response3 = doctor_agent.run(
"""Patient: 62-year-old female with Type 2 Diabetes
Chief Complaint: Follow-up for diabetes management
History:
- Diagnosed 8 years ago
- Recent labs: HbA1c 9.2%, FBG 180-220 mg/dL
- Current meds: Metformin 1000mg BID, Glipizide 10mg daily
- No hypoglycemic episodes
- BMI 32, sedentary lifestyle
- Reports good medication adherence
- No retinopathy, neuropathy, or nephropathy documented
Her diabetes is not adequately controlled. Please recommend treatment optimization."""
)
print("\n" + "="*70)
print("SCENARIO 3: Chronic Disease Management - Diabetes Optimization")
print("="*70)
print(response3)
# Scenario 4: Preventive medicine consultation
response4 = doctor_agent.run(
"""Patient: 50-year-old male, annual physical exam
History:
- Generally healthy, no major medical issues
- Father had MI at age 58, mother has hypertension
- Smoked 1 PPD for 20 years, quit 5 years ago
- Occasional alcohol (3-4 drinks/week)
- Sedentary job, exercises 1-2x/week
Vitals: BP 132/84, BMI 28, HR 72
Last labs (3 years ago): Total cholesterol 215, LDL 145, HDL 42
What preventive health screenings and interventions should be recommended?"""
)
print("\n" + "="*70)
print("SCENARIO 4: Preventive Medicine & Health Maintenance")
print("="*70)
print(response4)
