|
| 1 | +import os |
| 2 | +import json |
| 3 | +from datetime import datetime |
| 4 | +from typing import Dict, List, Optional |
| 5 | + |
| 6 | +import requests |
| 7 | +from loguru import logger |
| 8 | +from pydantic import BaseModel, Field |
| 9 | +from swarms import OpenAIChat |
| 10 | +from swarms import Agent |
| 11 | + |
| 12 | +# Ensure loguru logs are saved to a file |
| 13 | +logger.add("medinsight_pro_logs.log", rotation="500 MB") |
| 14 | +openai_api_key = os.getenv("OPENAI_API_KEY") |
| 15 | +semantic_scholar_api_key = os.getenv("SEMANTIC_SCHOLAR_API_KEY") |
| 16 | +pubmed_api_key = os.getenv("PUBMED_API_KEY") |
| 17 | + |
| 18 | + |
| 19 | +# Define the Pydantic schema for logging metadata |
| 20 | +class MedInsightMetadata(BaseModel): |
| 21 | + query: str = Field( |
| 22 | + ..., description="The task or query sent to the agent" |
| 23 | + ) |
| 24 | + pubmed_results: Optional[Dict] = Field( |
| 25 | + None, description="Results fetched from PubMed" |
| 26 | + ) |
| 27 | + semantic_scholar_results: Optional[Dict] = Field( |
| 28 | + None, description="Results fetched from Semantic Scholar" |
| 29 | + ) |
| 30 | + combined_summary: Optional[str] = Field( |
| 31 | + None, description="Final summarized output from the agent" |
| 32 | + ) |
| 33 | + timestamp: datetime = Field( |
| 34 | + default_factory=datetime.utcnow, |
| 35 | + description="Time the request was processed", |
| 36 | + ) |
| 37 | + status: str = Field( |
| 38 | + ..., |
| 39 | + description="Status of the agent task, e.g., success or failure", |
| 40 | + ) |
| 41 | + |
| 42 | + class Config: |
| 43 | + schema_extra = { |
| 44 | + "example": { |
| 45 | + "query": "COVID-19 treatments", |
| 46 | + "pubmed_results": { |
| 47 | + "paper_id": {"title": "COVID-19 vaccine trials"} |
| 48 | + }, |
| 49 | + "semantic_scholar_results": { |
| 50 | + "paper_id": { |
| 51 | + "title": "Effectiveness of mRNA vaccines" |
| 52 | + } |
| 53 | + }, |
| 54 | + "combined_summary": "Recent studies highlight the efficacy of mRNA vaccines in preventing COVID-19...", |
| 55 | + "timestamp": "2023-09-10T12:00:00Z", |
| 56 | + "status": "success", |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | +# Create an instance of the OpenAIChat class with GPT-4 |
| 62 | +model = OpenAIChat( |
| 63 | + api_key=openai_api_key, |
| 64 | + model_name="gpt-4", |
| 65 | + temperature=0.1, # Maintain a lower temperature for more focused summarization |
| 66 | +) |
| 67 | + |
| 68 | +# Define the system prompt |
| 69 | +med_sys_prompt = """ |
| 70 | +You are a highly knowledgeable Medical Research Summarization Agent. |
| 71 | +Your task is to read large volumes of medical research papers and generate concise summaries. |
| 72 | +Highlight potential treatments, ongoing clinical trials, medical breakthroughs, and important medical insights. |
| 73 | +You will focus on clarity, relevance, and precision, ensuring the summaries are actionable for doctors and researchers. |
| 74 | +""" |
| 75 | + |
| 76 | + |
| 77 | +# Initialize the Medical Summarization Agent |
| 78 | +agent = Agent( |
| 79 | + agent_name="Medical-Summarization-Agent", # Custom agent name |
| 80 | + system_prompt=med_sys_prompt, |
| 81 | + llm=model, |
| 82 | + max_loops=3, # Adjust loop count based on summarization needs |
| 83 | + autosave=True, |
| 84 | + dashboard=False, |
| 85 | + verbose=True, |
| 86 | + dynamic_temperature_enabled=False, # Disable temperature changes for consistency |
| 87 | + saved_state_path="medical_summarization_agent.json", # Path to save agent state |
| 88 | + user_name="medical_researcher", # Can be adjusted per user |
| 89 | + retry_attempts=2, |
| 90 | + context_length=100000, # Adjust based on summarization needs |
| 91 | + return_step_meta=False, |
| 92 | +) |
| 93 | + |
| 94 | + |
| 95 | +# Define the MedInsightPro class with customizable options and logging |
| 96 | +class MedInsightPro: |
| 97 | + def __init__( |
| 98 | + self, |
| 99 | + openai_api_key: str, |
| 100 | + pubmed_api_key: str = None, |
| 101 | + semantic_scholar_api_key: str = None, |
| 102 | + system_prompt: str = med_sys_prompt, |
| 103 | + agent: Agent = agent, |
| 104 | + ): |
| 105 | + self.openai_api_key = openai_api_key |
| 106 | + self.pubmed_api_key = pubmed_api_key |
| 107 | + self.semantic_scholar_api_key = semantic_scholar_api_key |
| 108 | + self.system_prompt = system_prompt |
| 109 | + self.agent = agent |
| 110 | + |
| 111 | + # Initialize the metadata history log |
| 112 | + self.metadata_log: List[MedInsightMetadata] = [] |
| 113 | + |
| 114 | + # Function to access PubMed data |
| 115 | + def fetch_pubmed_data(self, query, max_results=10): |
| 116 | + logger.info(f"Fetching data from PubMed for query: {query}") |
| 117 | + url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" |
| 118 | + params = { |
| 119 | + "db": "pubmed", |
| 120 | + "term": query, |
| 121 | + "retmax": max_results, |
| 122 | + "api_key": self.pubmed_api_key, |
| 123 | + "retmode": "json", |
| 124 | + } |
| 125 | + response = requests.get(url, params=params) |
| 126 | + data = response.json() |
| 127 | + ids = data.get("esearchresult", {}).get("idlist", []) |
| 128 | + |
| 129 | + if ids: |
| 130 | + id_str = ",".join(ids) |
| 131 | + fetch_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi" |
| 132 | + fetch_params = { |
| 133 | + "db": "pubmed", |
| 134 | + "id": id_str, |
| 135 | + "retmode": "json", |
| 136 | + } |
| 137 | + fetch_response = requests.get( |
| 138 | + fetch_url, params=fetch_params |
| 139 | + ) |
| 140 | + return fetch_response.json() |
| 141 | + return {} |
| 142 | + |
| 143 | + # Function to access Semantic Scholar data |
| 144 | + def fetch_semantic_scholar_data(self, query, max_results=10): |
| 145 | + logger.info( |
| 146 | + f"Fetching data from Semantic Scholar for query: {query}" |
| 147 | + ) |
| 148 | + url = "https://api.semanticscholar.org/graph/v1/paper/search" |
| 149 | + headers = {"x-api-key": self.semantic_scholar_api_key} |
| 150 | + params = {"query": query, "limit": max_results} |
| 151 | + response = requests.get(url, headers=headers, params=params) |
| 152 | + return response.json() |
| 153 | + |
| 154 | + # Method to run the agent with a given task |
| 155 | + def run(self, task: str): |
| 156 | + logger.info(f"Running MedInsightPro agent for task: {task}") |
| 157 | + status = "success" |
| 158 | + pubmed_data, semantic_scholar_data = {}, {} |
| 159 | + combined_summary = "" |
| 160 | + |
| 161 | + try: |
| 162 | + # Fetch data from PubMed |
| 163 | + if self.pubmed_api_key: |
| 164 | + pubmed_data = self.fetch_pubmed_data(task) |
| 165 | + |
| 166 | + # Fetch data from Semantic Scholar |
| 167 | + if self.semantic_scholar_api_key: |
| 168 | + semantic_scholar_data = ( |
| 169 | + self.fetch_semantic_scholar_data(task) |
| 170 | + ) |
| 171 | + |
| 172 | + # Summarize data with GPT-4 |
| 173 | + combined_summary_input = f"PubMed Data: {pubmed_data}\nSemantic Scholar Data: {semantic_scholar_data}" |
| 174 | + combined_summary = self.agent.run(combined_summary_input) |
| 175 | + logger.info(f"Summarization completed for task: {task}") |
| 176 | + except Exception as e: |
| 177 | + logger.error( |
| 178 | + f"Error during processing task: {task}. Error: {e}" |
| 179 | + ) |
| 180 | + status = "failure" |
| 181 | + |
| 182 | + # Log metadata |
| 183 | + metadata = MedInsightMetadata( |
| 184 | + query=task, |
| 185 | + pubmed_results=pubmed_data, |
| 186 | + semantic_scholar_results=semantic_scholar_data, |
| 187 | + combined_summary=combined_summary, |
| 188 | + status=status, |
| 189 | + ) |
| 190 | + self.metadata_log.append(metadata) |
| 191 | + |
| 192 | + # Save log to a JSON file |
| 193 | + self.save_metadata_log() |
| 194 | + |
| 195 | + return combined_summary |
| 196 | + |
| 197 | + # Method to save the metadata log to a JSON file |
| 198 | + def save_metadata_log(self): |
| 199 | + log_file = "medinsight_pro_history.json" |
| 200 | + with open(log_file, "w") as f: |
| 201 | + json.dump( |
| 202 | + [metadata.dict() for metadata in self.metadata_log], |
| 203 | + f, |
| 204 | + indent=4, |
| 205 | + ) |
| 206 | + logger.info(f"Metadata log saved to {log_file}") |
0 commit comments