# Medical Diagnosis Swarm Architecture
[![Join our Discord](https://img.shields.io/badge/Discord-Join%20our%20server-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/agora-999382051935506503) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@kyegomez3242) [![Connect on LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/kye-g-38759a207/) [![Follow on X.com](https://img.shields.io/badge/X.com-Follow-1DA1F2?style=for-the-badge&logo=x&logoColor=white)](https://x.com/kyegomezb)
MedicalSwarm is a sophisticated medical diagnosis and coding platform that leverages a coordinated swarm of specialized AI agents to deliver comprehensive medical assessments, accurate ICD-10 coding, and detailed clinical documentation. The system employs a hierarchical approach with specialized agents working in concert to analyze patient data, generate diagnoses, and ensure coding compliance.
## Key Features
### Multi-Agent Architecture
- Chief Medical Officer: Coordinates diagnosis workflow and synthesizes findings
- Virologist: Specializes in viral disease analysis and progression
- Internist: Provides comprehensive internal medicine evaluation
- Medical Coder: Ensures accurate ICD-10 coding and compliance
- Diagnostic Synthesizer: Creates final integrated assessments
### Enterprise Integration
- RAG (Retrieval-Augmented Generation) API support
- Comprehensive logging and telemetry
- Scalable batch processing capabilities
- Configurable output formats and storage
### Clinical Documentation
- Automated ICD-10 code assignment
- Hierarchical Condition Category (HCC) coding
- Evidence-based diagnostic rationale
- Detailed clinical progression timelines
-----
## Installation
```bash
pip install mcs
```
## Onboarding
To get started you must first set some envs in your `.env`
```env
WORKSPACE_DIR="agent_workspace"
OPENAI_API_KEY="your_key"
MASTER_KEY="328928402" # your master key for security
```
## Usage
```python
from mcs.main import MedicalCoderSwarm
import json
if __name__ == "__main__":
# Example patient case
patient_case = """
Patient: 45-year-old White Male
Location: New York, NY
Lab Results:
- egfr
- 59 ml / min / 1.73
- non african-american
"""
swarm = MedicalCoderSwarm(patient_id="Patient-001", max_loops=1, patient_documentation="")
swarm.run(task=patient_case)
print(json.dumps(swarm.to_dict()))
```
## Example with HIPPA Grade Security
```python
import json
from mcs.main import MedicalCoderSwarm
if __name__ == "__main__":
# Extended Example Patient Case
patient_case = """
Patient Information:
- Name: John Doe
- Age: 45
- Gender: Male
- Ethnicity: White
- Location: New York, NY
- BMI: 28.5 (Overweight)
- Occupation: Office Worker
Presenting Complaints:
- Persistent fatigue for 3 months
- Swelling in lower extremities
- Difficulty concentrating (brain fog)
- Increased frequency of urination
Medical History:
- Hypertension (diagnosed 5 years ago, poorly controlled)
- Type 2 Diabetes Mellitus (diagnosed 2 years ago, HbA1c: 8.2%)
- Family history of chronic kidney disease (mother)
Current Medications:
- Lisinopril 20 mg daily
- Metformin 1000 mg twice daily
- Atorvastatin 10 mg daily
Lab Results:
- eGFR: 59 ml/min/1.73m² (Non-African American)
- Serum Creatinine: 1.5 mg/dL
- BUN: 22 mg/dL
- Potassium: 4.8 mmol/L
- HbA1c: 8.2%
- Urinalysis: Microalbuminuria detected (300 mg/g creatinine)
Vital Signs:
- Blood Pressure: 145/90 mmHg
- Heart Rate: 78 bpm
- Respiratory Rate: 16 bpm
- Temperature: 98.6°F
- Oxygen Saturation: 98%
Differential Diagnoses to Explore:
1. Chronic Kidney Disease (CKD) Stage 3
2. Diabetic Nephropathy
3. Secondary Hypertension (due to CKD)
4. Fatigue related to poorly controlled diabetes
Specialist Consultations Needed:
- Nephrologist
- Endocrinologist
- Dietitian for diabetic and CKD management
Initial Management Recommendations:
- Optimize blood pressure control (<130/80 mmHg target for CKD)
- Glycemic control improvement (target HbA1c <7%)
- Lifestyle modifications: low-sodium, renal-friendly diet
- Referral to nephrologist for further evaluation
"""
# Initialize the MedicalCoderSwarm with the detailed patient case
swarm = MedicalCoderSwarm(
patient_id="Patient-001",
max_loops=1,
# patient_documentation=patient_case,
output_folder_path="reports",
key_storage_path="example_key.key",
)
# Run the swarm on the patient case
output = swarm.run(task=patient_case)
# Print the system's state after processing
print(json.dumps(swarm.to_dict(), indent=4))
```
## Architecture Overview
```mermaid
flowchart TB
CMO[Chief Medical Officer] --> V[Virologist]
V --> I[Internist]
I --> MC[Medical Coder]
MC --> S[Synthesizer]
```
## Features
- **Specialized Agent Roles**: Each agent has specific medical expertise and responsibilities
- **Structured Diagnostic Flow**: Organized pipeline from initial assessment to final synthesis
- **ICD-10 Coding Integration**: Comprehensive medical coding at each diagnostic stage
- **Automated Report Generation**: Standardized medical and coding reports
- **Evidence-Based Decision Making**: Multi-stage verification and synthesis process
## Agent Responsibilities
```mermaid
mindmap
root((Medical Swarm))
Chief Medical Officer
Initial Assessment
Coordinate Specialists
Treatment Plans
Lab Range Analysis
Virologist
Viral Analysis
Disease Progression
Risk Assessment
Internist
System Review
Vitals Analysis
Comorbidity Evaluation
Medical Coder
ICD-10 Assignment
Coding Compliance
Documentation Review
Synthesizer
Integration
Reconciliation
Final Assessment
```
## Diagnostic Flow Process
```mermaid
sequenceDiagram
participant P as Patient Case
participant CMO as Chief Medical Officer
participant V as Virologist
participant I as Internist
participant MC as Medical Coder
participant S as Synthesizer
P->>CMO: Initial Data
CMO->>V: Preliminary Assessment
V->>I: Viral Analysis
I->>MC: Comprehensive Review
MC->>S: Coded Diagnosis
S->>P: Final Report
```
## API Usage
We have established an api in the `/api` folder. To run the api locally you must git clone, and then run:
```bash
cd api
chmod +x bootup.sh
./bootup.sh
```
### API Testing
When you launch your api you can run the tests to see if it works ;)
```bash
cd api
python3 test.py
```
## Docker Usage
To build and run the Docker container for the Medical Coder Swarm, follow these steps:
1. **Build the Docker Image**:
```bash
docker build -t mcs .
```
2. **Run the Docker Container**:
```bash
docker run --rm mcs
```
## Docker Compose
```bash
docker-compose up
```
### To stop the services, run:
```bash
docker-compose down
```
# Full Diagram
```
graph TB
subgraph External["External Systems"]
API[("FastAPI Endpoints")]
RAG["RAG System"]
SEC["Security Layer"]
end
subgraph Core["Core MCS"]
MS["MedicalCoderSwarm"]
AG["AgentRearrange"]
subgraph Agents["Agent Network"]
CMO["Chief Medical Officer"]
VIR["Virologist"]
INT["Internist"]
MC["Medical Coder"]
SYN["Synthesizer"]
SUM["Summarizer"]
end
subgraph Security["Security Components"]
SDH["SecureDataHandler"]
KRP["KeyRotationPolicy"]
end
subgraph IO["I/O Management"]
LOG["Logger"]
FS["File System"]
end
end
%% Connections
API --> MS
MS --> AG
AG --> Agents
RAG --> MS
MS --> SDH
SDH --> KRP
MS --> LOG
MS --> FS
%% Agent Flow
CMO --> VIR
VIR --> INT
INT --> MC
MC --> SYN
SYN --> SUM
class API,RAG,SEC external
class MS,AG core
class SDH,KRP security
class LOG,FS io
```
## Lab Range Analysis
The system includes specialized functionality for analyzing lab results against diagnostic criteria:
- Automated range checking for common tests (e.g., eGFR)
- Diagnosis-specific range validation
- Multi-factor analysis for complex diagnoses
## Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
- Built with the Swarms framework
- Utilizes GPT-4 for advanced medical reasoning
- ICD-10 coding standards compliance
## Contact
For questions and support, please open an issue in the repository.
Raw data
{
"_id": null,
"home_page": "https://github.com/The-Swarm-Corporation/MedicalCoderSwarm",
"name": "mcs",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.10",
"maintainer_email": null,
"keywords": "artificial intelligence, deep learning, optimizers, Prompt Engineering",
"author": "Kye Gomez",
"author_email": "kye@apac.ai",
"download_url": "https://files.pythonhosted.org/packages/1d/68/ba0ea3311a053962b967b7595c15297a38589ee09c493468fa3adc606f4c/mcs-0.0.9.tar.gz",
"platform": null,
"description": "# Medical Diagnosis Swarm Architecture\n\n\n[![Join our Discord](https://img.shields.io/badge/Discord-Join%20our%20server-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/agora-999382051935506503) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@kyegomez3242) [![Connect on LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/kye-g-38759a207/) [![Follow on X.com](https://img.shields.io/badge/X.com-Follow-1DA1F2?style=for-the-badge&logo=x&logoColor=white)](https://x.com/kyegomezb)\n\nMedicalSwarm is a sophisticated medical diagnosis and coding platform that leverages a coordinated swarm of specialized AI agents to deliver comprehensive medical assessments, accurate ICD-10 coding, and detailed clinical documentation. The system employs a hierarchical approach with specialized agents working in concert to analyze patient data, generate diagnoses, and ensure coding compliance.\n\n## Key Features\n\n### Multi-Agent Architecture\n\n- Chief Medical Officer: Coordinates diagnosis workflow and synthesizes findings\n- Virologist: Specializes in viral disease analysis and progression\n- Internist: Provides comprehensive internal medicine evaluation\n- Medical Coder: Ensures accurate ICD-10 coding and compliance\n- Diagnostic Synthesizer: Creates final integrated assessments\n\n\n### Enterprise Integration\n\n- RAG (Retrieval-Augmented Generation) API support\n- Comprehensive logging and telemetry\n- Scalable batch processing capabilities\n- Configurable output formats and storage\n\n\n### Clinical Documentation\n\n- Automated ICD-10 code assignment\n- Hierarchical Condition Category (HCC) coding\n- Evidence-based diagnostic rationale\n- Detailed clinical progression timelines\n\n\n-----\n\n## Installation\n\n```bash\npip install mcs\n```\n\n## Onboarding\nTo get started you must first set some envs in your `.env`\n\n```env\nWORKSPACE_DIR=\"agent_workspace\"\nOPENAI_API_KEY=\"your_key\"\nMASTER_KEY=\"328928402\" # your master key for security\n\n```\n\n## Usage\n\n```python\n\nfrom mcs.main import MedicalCoderSwarm\nimport json\n\nif __name__ == \"__main__\":\n # Example patient case\n patient_case = \"\"\"\n Patient: 45-year-old White Male\n Location: New York, NY\n\n Lab Results:\n - egfr \n - 59 ml / min / 1.73\n - non african-american\n \n \"\"\"\n \n swarm = MedicalCoderSwarm(patient_id=\"Patient-001\", max_loops=1, patient_documentation=\"\")\n \n swarm.run(task=patient_case)\n \n print(json.dumps(swarm.to_dict()))\n```\n\n\n## Example with HIPPA Grade Security\n\n```python\n\nimport json\nfrom mcs.main import MedicalCoderSwarm\n\nif __name__ == \"__main__\":\n # Extended Example Patient Case\n patient_case = \"\"\"\n Patient Information:\n - Name: John Doe\n - Age: 45\n - Gender: Male\n - Ethnicity: White\n - Location: New York, NY\n - BMI: 28.5 (Overweight)\n - Occupation: Office Worker\n\n Presenting Complaints:\n - Persistent fatigue for 3 months\n - Swelling in lower extremities\n - Difficulty concentrating (brain fog)\n - Increased frequency of urination\n\n Medical History:\n - Hypertension (diagnosed 5 years ago, poorly controlled)\n - Type 2 Diabetes Mellitus (diagnosed 2 years ago, HbA1c: 8.2%)\n - Family history of chronic kidney disease (mother)\n\n Current Medications:\n - Lisinopril 20 mg daily\n - Metformin 1000 mg twice daily\n - Atorvastatin 10 mg daily\n\n Lab Results:\n - eGFR: 59 ml/min/1.73m\u00b2 (Non-African American)\n - Serum Creatinine: 1.5 mg/dL\n - BUN: 22 mg/dL\n - Potassium: 4.8 mmol/L\n - HbA1c: 8.2%\n - Urinalysis: Microalbuminuria detected (300 mg/g creatinine)\n\n Vital Signs:\n - Blood Pressure: 145/90 mmHg\n - Heart Rate: 78 bpm\n - Respiratory Rate: 16 bpm\n - Temperature: 98.6\u00b0F\n - Oxygen Saturation: 98%\n\n Differential Diagnoses to Explore:\n 1. Chronic Kidney Disease (CKD) Stage 3\n 2. Diabetic Nephropathy\n 3. Secondary Hypertension (due to CKD)\n 4. Fatigue related to poorly controlled diabetes\n\n Specialist Consultations Needed:\n - Nephrologist\n - Endocrinologist\n - Dietitian for diabetic and CKD management\n\n Initial Management Recommendations:\n - Optimize blood pressure control (<130/80 mmHg target for CKD)\n - Glycemic control improvement (target HbA1c <7%)\n - Lifestyle modifications: low-sodium, renal-friendly diet\n - Referral to nephrologist for further evaluation\n \"\"\"\n\n # Initialize the MedicalCoderSwarm with the detailed patient case\n swarm = MedicalCoderSwarm(\n patient_id=\"Patient-001\",\n max_loops=1,\n # patient_documentation=patient_case,\n output_folder_path=\"reports\",\n key_storage_path=\"example_key.key\",\n )\n\n # Run the swarm on the patient case\n output = swarm.run(task=patient_case)\n\n # Print the system's state after processing\n print(json.dumps(swarm.to_dict(), indent=4))\n```\n\n## Architecture Overview\n\n```mermaid\nflowchart TB\n CMO[Chief Medical Officer] --> V[Virologist]\n V --> I[Internist]\n I --> MC[Medical Coder]\n MC --> S[Synthesizer]\n \n```\n\n## Features\n\n- **Specialized Agent Roles**: Each agent has specific medical expertise and responsibilities\n- **Structured Diagnostic Flow**: Organized pipeline from initial assessment to final synthesis\n- **ICD-10 Coding Integration**: Comprehensive medical coding at each diagnostic stage\n- **Automated Report Generation**: Standardized medical and coding reports\n- **Evidence-Based Decision Making**: Multi-stage verification and synthesis process\n\n## Agent Responsibilities\n\n```mermaid\nmindmap\n root((Medical Swarm))\n Chief Medical Officer\n Initial Assessment\n Coordinate Specialists\n Treatment Plans\n Lab Range Analysis\n Virologist\n Viral Analysis\n Disease Progression\n Risk Assessment\n Internist\n System Review\n Vitals Analysis\n Comorbidity Evaluation\n Medical Coder\n ICD-10 Assignment\n Coding Compliance\n Documentation Review\n Synthesizer\n Integration\n Reconciliation\n Final Assessment\n```\n\n## Diagnostic Flow Process\n\n```mermaid\nsequenceDiagram\n participant P as Patient Case\n participant CMO as Chief Medical Officer\n participant V as Virologist\n participant I as Internist\n participant MC as Medical Coder\n participant S as Synthesizer\n \n P->>CMO: Initial Data\n CMO->>V: Preliminary Assessment\n V->>I: Viral Analysis\n I->>MC: Comprehensive Review\n MC->>S: Coded Diagnosis\n S->>P: Final Report\n```\n\n\n## API Usage\nWe have established an api in the `/api` folder. To run the api locally you must git clone, and then run:\n\n```bash\ncd api\n\nchmod +x bootup.sh\n\n./bootup.sh\n\n```\n\n### API Testing\nWhen you launch your api you can run the tests to see if it works ;)\n\n```bash\ncd api\n\npython3 test.py\n```\n\n## Docker Usage\n\nTo build and run the Docker container for the Medical Coder Swarm, follow these steps:\n\n1. **Build the Docker Image**:\n ```bash\n docker build -t mcs .\n ```\n\n2. **Run the Docker Container**:\n ```bash\n docker run --rm mcs\n ```\n\n## Docker Compose\n\n```bash\ndocker-compose up\n```\n\n### To stop the services, run:\n```bash\ndocker-compose down\n```\n\n\n# Full Diagram\n\n```\ngraph TB\n subgraph External[\"External Systems\"]\n API[(\"FastAPI Endpoints\")]\n RAG[\"RAG System\"]\n SEC[\"Security Layer\"]\n end\n\n subgraph Core[\"Core MCS\"]\n MS[\"MedicalCoderSwarm\"]\n AG[\"AgentRearrange\"]\n \n subgraph Agents[\"Agent Network\"]\n CMO[\"Chief Medical Officer\"]\n VIR[\"Virologist\"]\n INT[\"Internist\"]\n MC[\"Medical Coder\"]\n SYN[\"Synthesizer\"]\n SUM[\"Summarizer\"]\n end\n \n subgraph Security[\"Security Components\"]\n SDH[\"SecureDataHandler\"]\n KRP[\"KeyRotationPolicy\"]\n end\n \n subgraph IO[\"I/O Management\"]\n LOG[\"Logger\"]\n FS[\"File System\"]\n end\n end\n\n %% Connections\n API --> MS\n MS --> AG\n AG --> Agents\n RAG --> MS\n MS --> SDH\n SDH --> KRP\n MS --> LOG\n MS --> FS\n \n %% Agent Flow\n CMO --> VIR\n VIR --> INT\n INT --> MC\n MC --> SYN\n SYN --> SUM\n \n class API,RAG,SEC external\n class MS,AG core\n class SDH,KRP security\n class LOG,FS io\n\n\n```\n\n\n\n## Lab Range Analysis\n\nThe system includes specialized functionality for analyzing lab results against diagnostic criteria:\n\n- Automated range checking for common tests (e.g., eGFR)\n- Diagnosis-specific range validation\n- Multi-factor analysis for complex diagnoses\n\n## Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/AmazingFeature`)\n3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)\n4. Push to the branch (`git push origin feature/AmazingFeature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details\n\n## Acknowledgments\n\n- Built with the Swarms framework\n- Utilizes GPT-4 for advanced medical reasoning\n- ICD-10 coding standards compliance\n\n## Contact\n\nFor questions and support, please open an issue in the repository.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Paper - Pytorch",
"version": "0.0.9",
"project_urls": {
"Documentation": "https://github.com/The-Swarm-Corporation/MedicalCoderSwarm",
"Homepage": "https://github.com/The-Swarm-Corporation/MedicalCoderSwarm",
"Repository": "https://github.com/The-Swarm-Corporation/MedicalCoderSwarm"
},
"split_keywords": [
"artificial intelligence",
" deep learning",
" optimizers",
" prompt engineering"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "e4bf235f58e8b45c81bb41ffed4e90dd0fe5d7e71bd395b504cc93f005b46775",
"md5": "7b6a17d220423a577966b045749d4d2f",
"sha256": "90fccf4d9f0ed5e61b3a56085c0152e3eae7914ecd4d068c55944f31dfe36de8"
},
"downloads": -1,
"filename": "mcs-0.0.9-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7b6a17d220423a577966b045749d4d2f",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.10",
"size": 20613,
"upload_time": "2025-01-12T06:18:06",
"upload_time_iso_8601": "2025-01-12T06:18:06.836400Z",
"url": "https://files.pythonhosted.org/packages/e4/bf/235f58e8b45c81bb41ffed4e90dd0fe5d7e71bd395b504cc93f005b46775/mcs-0.0.9-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "1d68ba0ea3311a053962b967b7595c15297a38589ee09c493468fa3adc606f4c",
"md5": "81f0e6ddafcc6a638513dbc6ce9702ca",
"sha256": "d4c48eb1b143adbd22f945f3135401326262d2a667c48a519586fea86c1e4b7c"
},
"downloads": -1,
"filename": "mcs-0.0.9.tar.gz",
"has_sig": false,
"md5_digest": "81f0e6ddafcc6a638513dbc6ce9702ca",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.10",
"size": 22809,
"upload_time": "2025-01-12T06:18:09",
"upload_time_iso_8601": "2025-01-12T06:18:09.861183Z",
"url": "https://files.pythonhosted.org/packages/1d/68/ba0ea3311a053962b967b7595c15297a38589ee09c493468fa3adc606f4c/mcs-0.0.9.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-01-12 06:18:09",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "The-Swarm-Corporation",
"github_project": "MedicalCoderSwarm",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "swarms",
"specs": []
},
{
"name": "loguru",
"specs": []
},
{
"name": "swarm-models",
"specs": []
},
{
"name": "cryptography",
"specs": []
},
{
"name": "python-dotenv",
"specs": []
},
{
"name": "pkg_resources",
"specs": []
},
{
"name": "setuptools",
"specs": []
}
],
"lcname": "mcs"
}