CoMed: A framework for analyzing co-medication risks using Chain-of-Thought reasoning.
Project description
CoMed: A Framework for Drug Co-Medication Risk Analysis
๐ฏ Overview
CoMed is a comprehensive framework for analyzing drug co-medication risks using a modular architecture that supports RAG (Retrieval-Augmented Generation), CoT (Chain-of-Thought reasoning), and Multi-Agent systems. This version addresses reviewer feedback by providing clear component separation, ablation study support, and true multi-agent collaboration.
๐ง Key Features
1. Modular Architecture
- RAG Module (
rag.py): Independent literature retrieval system - CoT Module (
cot.py): Chain-of-thought reasoning system - Multi-Agent Module (
agents.py): True agent-to-agent collaboration - Benchmark Module (
benchmark.py): Ablation studies and performance evaluation
2. Ablation Study Support
- Independent testing of each component's contribution
- Detailed performance comparison and analysis
- Automatic generation of ablation study reports
3. True Multi-Agent System
- Agent-to-agent communication and collaboration
- Specialized agents for different roles
- Agent state management and conversation tracking
๐ฆ Installation
pip install comed
๐ Quick Start
Basic Usage
import os
import comed
# Set required environment variables
os.environ["MODEL_NAME"] = "gpt-4o"
os.environ["API_BASE"] = "https://api.openai.com/v1"
os.environ["API_KEY"] = "your-api-key-here"
# Initialize system
drugs = ["warfarin", "aspirin", "ibuprofen"]
com = comed.CoMedData(drugs)
# Run full analysis
report_path = com.run_full_analysis(retmax=30, verbose=True)
print(f"Report generated at: {report_path}")
๐ Usage Examples
Example 1: Step-by-Step Analysis
import os
import comed
# Set API credentials
os.environ["MODEL_NAME"] = "gpt-4o"
os.environ["API_BASE"] = "https://api.openai.com/v1"
os.environ["API_KEY"] = "your-api-key-here"
# Create a CoMed instance
drugs = ["warfarin", "aspirin", "penicillin"]
com = comed.CoMedData(drugs)
# Search PubMed for literature
com.search(retmax=20, email="your.email@example.com")
# Analyze which papers mention drug combinations
com.analyze_associations()
# Evaluate risks across multiple dimensions
com.analyze_risks()
# Generate an HTML report
com.generate_report("Anticoagulant_Report.html")
Example 2: Method Chaining
import os
import comed
# Set API credentials
os.environ["MODEL_NAME"] = "gpt-4o"
os.environ["API_BASE"] = "https://api.openai.com/v1"
os.environ["API_KEY"] = "your-api-key-here"
# Create a CoMed instance and run analysis pipeline with method chaining
drugs = ["ibuprofen", "naproxen", "acetaminophen"]
com = comed.CoMedData(drugs)
com.search(retmax=30) \
.analyze_associations() \
.analyze_risks() \
.generate_report("NSAID_Interactions.html")
Example 3: Adding Drugs Incrementally
import os
import comed
# Set API credentials
os.environ["MODEL_NAME"] = "gpt-4o"
os.environ["API_BASE"] = "https://api.openai.com/v1"
os.environ["API_KEY"] = "your-api-key-here"
# Start with a smaller set of drugs
com = comed.CoMedData(["warfarin", "aspirin"])
com.search(retmax=30)
# Add more drugs later
com.add_drugs(["heparin", "clopidogrel"])
# Only search for the new combinations
com.search(retmax=30)
# Complete the analysis pipeline
com.analyze_associations() \
.analyze_risks() \
.generate_report("Expanded_Drug_Report.html")
Example 4: Ablation Study
import comed
# Initialize system
drugs = ["metformin", "lisinopril", "atorvastatin"]
com = comed.CoMedData(drugs)
# Run ablation study
ablation_results = com.run_ablation_study(retmax=20, verbose=True)
# View results
print("Ablation Study Results:")
for stage, result in ablation_results["ablation_results"].items():
if stage != "ablation_report":
print(f"{stage}: {result['time']:.1f}s, Papers: {result['stats']['total_papers']}")
# Component comparison
comparison_results = com.compare_components(retmax=20, verbose=True)
report = comparison_results["comparison_report"]
print("\nPerformance Comparison:")
for component, perf in report["performance_summary"].items():
print(f"{component}: {perf['time']:.1f}s, Efficiency: {perf['efficiency']:.2f}")
Example 5: Multi-Agent System
from comed import MultiAgentSystem
# Initialize multi-agent system
agent_system = MultiAgentSystem(
model_name="gpt-4o",
api_key="your-key",
api_base="https://api.openai.com/v1"
)
# Process drug combination
drug1, drug2 = "warfarin", "aspirin"
abstract = "Literature abstract content..."
# Multi-agent collaboration analysis
result = agent_system.process_drug_combination(drug1, drug2, abstract)
print("Multi-Agent Analysis Results:")
print(f"Risk Analysis: {result['risk_analysis']}")
print(f"Safety Assessment: {result['safety_assessment']}")
print(f"Clinical Recommendation: {result['clinical_recommendation']}")
๐ฎ Demo Examples
Run the comprehensive demo to see CoMed in action:
# Run basic demo
python examples/basic_demo.py
# Run ablation study demo
python examples/ablation_study_example.py
# Run quick start demo
python examples/quick_start.py
Using Existing Data
If you already have association data (e.g., ddc_papers_association_pd.csv), you can skip the search and analysis steps:
# Load existing data and run multi-agent analysis
python examples/load_and_analyze.py
# Simple multi-agent test
python examples/simple_agent_test.py
# Direct multi-agent test
python examples/direct_agent_test.py
The demo includes:
- Basic usage examples
- Step-by-step analysis
- Method chaining
- Incremental drug addition
- Data persistence
- Ablation studies
- Multi-agent collaboration
- Direct multi-agent testing with existing data
๐ง Advanced Configuration
Environment Variables
export MODEL_NAME="gpt-4o"
export API_BASE="https://api.openai.com/v1"
export API_KEY="your-api-key"
export LOG_DIR="logs"
Custom Configuration
# Configure LLM
com = comed.CoMedData(["warfarin", "aspirin"])
com.set_config({
'model_name': 'gpt-4o',
'api_base': 'https://api.openai.com/v1',
'api_key': 'your-key'
})
๐ Performance Evaluation
Ablation Study Metrics
- Time Efficiency: Processing time for each component
- Quality Metrics: Positive association rate, accuracy
- Component Contributions: Independent contribution of each component
- Efficiency Analysis: Balance between processing speed and quality
Benchmark Testing
from comed import CoMedBenchmark
# Initialize benchmark system
benchmark = CoMedBenchmark(
model_name="gpt-4o",
api_key="your-key",
api_base="https://api.openai.com/v1"
)
# Test drug combinations
drug_combinations = [
["warfarin", "aspirin"],
["metformin", "lisinopril"],
["atorvastatin", "amlodipine"]
]
# Run ablation study
ablation_results = benchmark.run_ablation_study(
drug_combinations, retmax=20, verbose=True
)
# Save results
results_file = benchmark.save_benchmark_results(ablation_results)
print(f"Benchmark results saved to: {results_file}")
๐๏ธ Architecture Design
Modular Design
CoMed v2.0
โโโ RAG Module (rag.py)
โ โโโ Literature retrieval
โ โโโ Relevance filtering
โ โโโ Statistics
โโโ CoT Module (cot.py)
โ โโโ Chain-of-thought reasoning
โ โโโ Step-by-step analysis
โ โโโ Result formatting
โโโ Multi-Agent Module (agents.py)
โ โโโ Base agent class
โ โโโ Specialized agents
โ โโโ Agent collaboration
โโโ Benchmark Module (benchmark.py)
โ โโโ Ablation studies
โ โโโ Performance evaluation
โ โโโ Report generation
โโโ Core Module (core.py)
โโโ Component integration
โโโ Configuration management
โโโ Result aggregation
Data Flow
Drug Combinations โ RAG Retrieval โ CoT Reasoning โ Multi-Agent Analysis โ Result Integration โ Report Generation
โ โ โ โ โ
Literature Database Association Analysis Risk Assessment Clinical Recommendations Final Report
๐ API Reference
Core Classes
CoMedData: Main analysis classRAGSystem: RAG retrieval systemCoTReasoner: CoT reasoning systemMultiAgentSystem: Multi-agent systemCoMedBenchmark: Benchmark testing system
Key Methods
run_full_analysis(): Run complete analysis pipelinerun_ablation_study(): Run ablation studyrun_component_test(): Test individual componentcompare_components(): Compare component performanceset_config(): Set configuration
Environment Variables
MODEL_NAME: Name of the LLM to use (e.g., "gpt-4o", "qwen2.5-32b-instruct")API_BASE: Base URL for the LLM APIAPI_KEY: API key for LLM accessLOG_DIR: Directory to store log filesOLD_OPENAI_API: Whether to use the old OpenAI API format ("Yes" or "No")
๐ ๏ธ Development
Adding New Components
from comed.agents import Agent
class CustomAgent(Agent):
def __init__(self, model_name, api_key, api_base):
super().__init__("CustomAgent", "Custom Analysis", model_name, api_key, api_base)
def _execute_task(self, input_data):
# Implement custom analysis logic
return {"custom_result": "Analysis result"}
Custom Ablation Studies
# Create custom benchmark test
class CustomBenchmark(CoMedBenchmark):
def run_custom_ablation(self, drug_combinations):
# Implement custom ablation study logic
pass
๐ค Contributing
We welcome contributions in various forms:
- Code Contributions: New features, bug fixes, performance optimizations
- Documentation Improvements: Better examples, tutorials, API documentation
- Test Cases: Unit tests, integration tests, benchmark tests
- Ablation Studies: New evaluation metrics, test scenarios
๐ License
This project is licensed under the BSD License. See LICENSE file for details.
๐ Acknowledgments
Thanks to the reviewers for their valuable feedback, which helped us build a more modular, evaluable framework.
๐ Contact
- Project Homepage: https://github.com/studentiz/comed
- Issue Reports: Please use GitHub Issues
- Email: studentiz@live.com
Note: This framework is for research purposes only and should not be used for clinical decision-making. Any medical decisions should be made in consultation with qualified healthcare professionals.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file comed-2.0.1.tar.gz.
File metadata
- Download URL: comed-2.0.1.tar.gz
- Upload date:
- Size: 40.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.17
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
5164f0a3b3ea40247f230da5e6666336e8e21618766af97f65da8d690eeea0b3
|
|
| MD5 |
ab0cb705038d47880bc988919297d410
|
|
| BLAKE2b-256 |
c672481d922a5e1a1a1891422f7f718f84fbff48380245e8c29322e6c091b484
|
File details
Details for the file comed-2.0.1-py3-none-any.whl.
File metadata
- Download URL: comed-2.0.1-py3-none-any.whl
- Upload date:
- Size: 43.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.17
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e5df007e9c6c9b5c688219777fbcc4d4cf7b3f9232e224ba47b8f3941e6adccf
|
|
| MD5 |
b0fa5d93550b58a4a18a0e5f5c869c23
|
|
| BLAKE2b-256 |
e7c5c2477967bec2d2a35eb6b7de33b07f26bd8dd4421f73ca8f9fdd5bfabb9b
|