Skip to content

Commit 5fd300f

Browse files
author
Your Name
committed
[FUNCTION CALLER FOR MORE PRECISE QUERY]
1 parent 8bc1030 commit 5fd300f

5 files changed

+107
-107
lines changed

agent_workspace/Medical-Summarization-Agent_state.json

+8-8
Large diffs are not rendered by default.

logs/medinsight_pro_history_time:2024-09-20_23-07-13.json

Whitespace-only changes.

logs/medinsight_pro_history_time:2024-09-20_23-07-52.json

+1
Large diffs are not rendered by default.

medinsight/agent.py

+97-97
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
1-
import time
2-
import os
31
import json
4-
from typing import Dict, List, Optional
2+
import os
3+
import time
4+
from typing import Dict, List, Optional, Any
55

66
import requests
7+
from dotenv import load_dotenv
78
from loguru import logger
89
from pydantic import BaseModel, Field
9-
from swarms import OpenAIChat
10-
from swarms import Agent
11-
from dotenv import load_dotenv
10+
from swarm_models import OpenAIFunctionCaller
11+
from swarms import Agent, OpenAIChat
12+
1213
from medinsight.pub_med import query_pubmed_with_abstract
13-
from swarms import OpenAIFunctionCaller
1414

1515
load_dotenv()
1616

1717
# Ensure loguru logs are saved to a file
1818
logger.add("medinsight_pro_logs.log", rotation="500 MB")
1919
openai_api_key = os.getenv("OPENAI_API_KEY")
2020
semantic_scholar_api_key = os.getenv("SEMANTIC_SCHOLAR_API_KEY")
21-
pubmed_api_key = os.getenv("PUBMED_API_KEY")
2221
time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S")
2322

2423

@@ -27,7 +26,7 @@ class MedInsightMetadata(BaseModel):
2726
task: str = Field(
2827
..., description="The task or query sent to the agent"
2928
)
30-
query_agent_analysis: Dict[str, str]
29+
query_agent_analysis: Dict[str, Any]
3130
pubmed_results: Optional[List[Dict]] = Field(
3231
None, description="Results fetched from PubMed"
3332
)
@@ -44,17 +43,30 @@ class MedInsightMetadata(BaseModel):
4443
time_stamp: str = Field(
4544
time_stamp, description="Timestamp of the agent task"
4645
)
47-
loop: int = Field(
48-
0,
49-
)
5046

5147

5248
class MedInsightMetadataOutput(BaseModel):
53-
max_loops: int
54-
logs: List[MedInsightMetadata] = None
49+
task: str = Field(..., description=None)
50+
logs: List[MedInsightMetadata] = Field(None, description=None)
5551
time_stamp: str = Field(time_stamp, description=None)
5652

5753

54+
55+
class PubMedQuery(BaseModel):
56+
analysis_of_request: str = Field(
57+
...,
58+
description="Analyze the nature of the request, identifying the specific disease, virus, or condition. Consider the context of the inquiry, including symptoms, demographics, and relevant medical history to provide a comprehensive understanding.",
59+
)
60+
pubmed_query: str = Field(
61+
...,
62+
description="Formulate a precise PubMed query based on the analysis of the request. Ensure the query includes the disease or condition name, relevant keywords, and MeSH terms. Incorporate Boolean operators to enhance search accuracy and retrieve the most pertinent research articles, reviews, and clinical trials.",
63+
)
64+
max_articles: int = Field(
65+
...,
66+
description=None
67+
)
68+
69+
5870
# Create an instance of the OpenAIChat class with GPT-4
5971
model = OpenAIChat(
6072
openai_api_key=openai_api_key,
@@ -90,19 +102,13 @@ class MedInsightMetadataOutput(BaseModel):
90102
)
91103

92104

93-
class PubMedQuery(BaseModel):
94-
analysis_of_request: str = Field(
95-
...,
96-
description="Analyze the nature of the request, identifying the specific disease, virus, or condition. Consider the context of the inquiry, including symptoms, demographics, and relevant medical history to provide a comprehensive understanding.",
97-
)
98-
pubmed_query: str = Field(
99-
...,
100-
description="Formulate a precise PubMed query based on the analysis of the request. Ensure the query includes the disease or condition name, relevant keywords, and MeSH terms. Incorporate Boolean operators to enhance search accuracy and retrieve the most pertinent research articles, reviews, and clinical trials.",
101-
)
102-
103-
104105
# Define the MedInsightPro class with customizable options and logging
105106
class MedInsightPro:
107+
"""
108+
This class is used to initialize and run the MedInsight Pro agent.
109+
It allows for customization of various options and provides logging functionality.
110+
"""
111+
106112
def __init__(
107113
self,
108114
semantic_scholar_api_key: str = None,
@@ -112,6 +118,9 @@ def __init__(
112118
max_loops: int = None,
113119
return_json: bool = False,
114120
):
121+
"""
122+
Initialize the MedInsight Pro agent with the provided parameters.
123+
"""
115124
self.semantic_scholar_api_key = semantic_scholar_api_key
116125
self.system_prompt = system_prompt
117126
self.agent = agent
@@ -131,12 +140,16 @@ def __init__(
131140
self.metadata_log = MedInsightMetadataOutput(
132141
max_loops=max_loops,
133142
logs=[],
143+
task=""
134144
)
135145

136146
# Function to access Semantic Scholar data
137147
def fetch_semantic_scholar_data(
138148
self, query: str, max_results: int = 10
139149
):
150+
"""
151+
Fetch data from Semantic Scholar for the provided query.
152+
"""
140153
logger.info(
141154
f"Fetching data from Semantic Scholar for query: {query}"
142155
)
@@ -148,94 +161,81 @@ def fetch_semantic_scholar_data(
148161

149162
# Method to run the agent with a given task
150163

151-
def run(self, task: str, img: str = None, *args, **kwargs):
164+
def run(self, task: str, *args, **kwargs):
152165
logger.info(f"Running MedInsightPro agent for task: {task}")
166+
status = "success"
167+
# pubmed_data, semantic_scholar_data = {}, {}
153168
combined_summary = ""
154-
155-
# Run the structured output agent to get the initial query
169+
156170
analysis = self.precise_query_agent.run(task)
157-
pubmed_query = analysis["pubmed_query"]
158-
responses = []
159-
160-
# Initial response (the pubmed query)
161-
responses.append(pubmed_query)
162-
163-
loop = 0
164-
165-
for loop in range(self.max_loops):
166-
try:
167-
logger.info(
168-
f"Running loop {loop + 1}/{self.max_loops}"
169-
)
170-
171-
# Fetch data from PubMed based on the query
172-
pubmed_data, pubmed_dict = query_pubmed_with_abstract(
173-
query=pubmed_query,
174-
max_articles=self.max_articles,
175-
*args,
176-
**kwargs,
177-
)
178-
logger.info(f"PubMed data: {pubmed_data}")
179-
responses.append(pubmed_data)
180-
181-
# Fetch data from Semantic Scholar, if available
182-
if self.semantic_scholar_api_key:
183-
semantic_scholar_data = (
184-
self.fetch_semantic_scholar_data(task)
185-
)
186-
responses.append(semantic_scholar_data)
187-
188-
# Summarize data with GPT-4 using the agent
189-
if pubmed_data:
190-
combined_summary_input = pubmed_data
191-
else:
192-
combined_summary_input = semantic_scholar_data
193-
194-
# Feed the result back into the agent as input for the next loop
195-
combined_summary = self.agent.run(
196-
combined_summary_input, img, *args, **kwargs
197-
)
198-
responses.append(combined_summary)
199-
logger.info(
200-
f"Summarization completed for loop {loop + 1}"
201-
)
202-
203-
# Update the query for the next loop
204-
pubmed_query = combined_summary # Feed the output back as input for the next loop
205-
206-
# Log metadata for each loop iteration
207-
metadata = MedInsightMetadata(
208-
task=task,
209-
query_agent_analysis=analysis,
210-
pubmed_results=pubmed_dict,
211-
combined_summary=combined_summary,
212-
status="success",
213-
loop_responses=responses, # Track all loop responses
214-
time_stamp=time.strftime("%Y-%m-%d_%H-%M-%S"),
171+
logger.info(f"Pubmed query: {analysis}")
172+
173+
query = analysis["pubmed_query"]
174+
# num_articles = int(analysis["max_articles"])
175+
176+
try:
177+
# Fetch data from PubMed
178+
pubmed_data, pubmed_dict = query_pubmed_with_abstract(
179+
query=query, max_articles=self.max_articles, *args, **kwargs
180+
)
181+
print(pubmed_dict)
182+
logger.info(f"PubMed data: {pubmed_data}")
183+
184+
# Fetch data from Semantic Scholar
185+
if self.semantic_scholar_api_key:
186+
semantic_scholar_data = (
187+
self.fetch_semantic_scholar_data(task)
215188
)
216-
self.metadata_log.logs.append(metadata)
217189

218-
except Exception as e:
219-
logger.error(
220-
f"Error during loop {loop + 1}. Error: {e}"
221-
)
222-
raise e
190+
# Summarize data with GPT-4
191+
# combined_summary_input = f"PubMed Data: {pubmed_data}\nSemantic Scholar Data: {semantic_scholar_data}"
192+
if pubmed_data:
193+
combined_summary_input = pubmed_data
194+
else:
195+
combined_summary_input = semantic_scholar_data
196+
197+
combined_summary = self.agent.run(combined_summary_input)
198+
logger.info(f"Summarization completed for task: {task}")
199+
except Exception as e:
200+
logger.error(
201+
f"Error during processing task: {task}. Error: {e}"
202+
)
203+
status = "failure"
204+
raise e
205+
206+
# Log metadata
207+
metadata = MedInsightMetadata(
208+
task = task,
209+
query_agent_analysis=analysis,
210+
pubmed_results=pubmed_dict,
211+
combined_summary=combined_summary,
212+
status="success",
213+
time_stamp=time_stamp
214+
)
215+
self.metadata_log.logs.append(metadata)
223216

224-
# Save metadata log to a JSON file
217+
# Save log to a JSON file
225218
self.save_metadata_log()
226219

227-
# Return the final result in the desired format (JSON or summary)
220+
# return combined_summary
221+
228222
if self.return_json:
229-
return self.metadata_log.model_dump_json(indent=2)
223+
return self.metadata_log.model_dump_json()
224+
230225
else:
231226
return combined_summary
232-
227+
233228
# Method to save the metadata log to a JSON file
234229
def save_metadata_log(self):
230+
"""
231+
Save the metadata log to a JSON file.
232+
"""
235233
import time
236234

237235
time_stamp = time.strftime("%Y-%m-%d_%H-%M-%S")
238236
log_file = f"medinsight_pro_history_time:{time_stamp}.json"
237+
239238
with open(log_file, "w") as file:
240-
json.dump(self.metadata_log.model_dump, file)
239+
json.dump(self.metadata_log.model_dump(), file)
240+
241241
logger.info(f"Metadata log saved to {log_file}")

requirements.txt

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
torch
2-
zetascale
3-
swarms
2+
zetascale

0 commit comments

Comments
 (0)