Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -36,6 +36,7 @@ if not GROQ_API_KEY:
|
|
36 |
class GraphState:
|
37 |
"""State type for the graph."""
|
38 |
input: str
|
|
|
39 |
query: Optional[str] = None
|
40 |
ontology_results: Optional[str] = None
|
41 |
response: Optional[str] = None
|
@@ -52,18 +53,98 @@ class OntologyAgent:
|
|
52 |
logging.error(f"Failed to load ontology file: {e}")
|
53 |
raise ValueError(f"Failed to load ontology file: {e}")
|
54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
def create_agent_graph(owl_file_path: str) -> StateGraph:
|
56 |
"""Create a processing graph for drug interaction analysis using separate agents."""
|
57 |
analyzer = DrugInteractionAnalyzer(owl_file_path)
|
58 |
|
59 |
def user_input_node(state: GraphState) -> Dict[str, str]:
|
60 |
-
logging.info("Processing user input.")
|
61 |
-
return {"query": state.
|
62 |
|
63 |
def ontology_query_node(state: GraphState) -> Dict[str, str]:
|
64 |
try:
|
65 |
logging.info("Executing ontology queries.")
|
66 |
-
drug_names = [d.strip() for d in state.
|
67 |
results = analyzer.analyze_drugs(drug_names)
|
68 |
logging.info(f"Ontology query results: {results}")
|
69 |
return {"ontology_results": json.dumps(results, indent=2)}
|
@@ -76,6 +157,9 @@ def create_agent_graph(owl_file_path: str) -> StateGraph:
|
|
76 |
Based on the drug interaction analysis results:
|
77 |
{ontology_results}
|
78 |
|
|
|
|
|
|
|
79 |
Please provide a comprehensive summary of:
|
80 |
1. Direct interactions between the drugs
|
81 |
2. Potential conflicts
|
@@ -84,13 +168,14 @@ def create_agent_graph(owl_file_path: str) -> StateGraph:
|
|
84 |
|
85 |
If no results were found, please indicate this clearly.
|
86 |
Format the response in a clear, structured manner.
|
|
|
87 |
"""
|
88 |
|
89 |
prompt = ChatPromptTemplate.from_template(template)
|
90 |
|
91 |
try:
|
92 |
llm = ChatGroq(
|
93 |
-
model_name="
|
94 |
api_key=GROQ_API_KEY,
|
95 |
temperature=0.7
|
96 |
)
|
@@ -103,7 +188,9 @@ def create_agent_graph(owl_file_path: str) -> StateGraph:
|
|
103 |
|
104 |
try:
|
105 |
response = chain.invoke({
|
106 |
-
"ontology_results": state.ontology_results
|
|
|
|
|
107 |
})
|
108 |
|
109 |
logging.info("LLM processing completed successfully.")
|
@@ -112,16 +199,22 @@ def create_agent_graph(owl_file_path: str) -> StateGraph:
|
|
112 |
logging.error(f"Error processing results with LLM: {e}")
|
113 |
return {"response": f"Error processing results: {str(e)}"}
|
114 |
|
|
|
115 |
workflow = StateGraph(GraphState)
|
116 |
|
|
|
|
|
117 |
workflow.add_node("input_processor", user_input_node)
|
118 |
workflow.add_node("ontology_query", ontology_query_node)
|
119 |
workflow.add_node("llm_processing", llm_processing_node)
|
120 |
|
|
|
|
|
121 |
workflow.add_edge("input_processor", "ontology_query")
|
122 |
workflow.add_edge("ontology_query", "llm_processing")
|
123 |
|
124 |
-
|
|
|
125 |
|
126 |
logging.info("Agent graph created and configured successfully.")
|
127 |
|
@@ -205,7 +298,7 @@ def main():
|
|
205 |
user_input = st.text_input("", value="", key="drug_input", placeholder="e.g., Aspirin, Warfarin")
|
206 |
st.markdown('<style>div[data-testid="stTextInput"] input { font-size: 16px;}</style>', unsafe_allow_html=True)
|
207 |
|
208 |
-
if st.button("Analyze",type="primary"):
|
209 |
if not user_input.strip():
|
210 |
st.warning("Please enter at least one drug name.")
|
211 |
return
|
@@ -220,6 +313,10 @@ def main():
|
|
220 |
with st.spinner("Analyzing drug interactions..."):
|
221 |
agent_graph = create_agent_graph(owl_file_path)
|
222 |
result = agent_graph.invoke(GraphState(input=user_input))
|
|
|
|
|
|
|
|
|
223 |
|
224 |
st.subheader("Analysis Results:")
|
225 |
st.markdown(result["response"])
|
@@ -237,6 +334,6 @@ def main():
|
|
237 |
<p style='text-align: left; color: #d46c6c;'>Disclaimer: </p><p style='text-align: left; color: #707377;'>This application is intended for informational purposes only and does not replace professional medical advice, diagnosis, or treatment. The analysis provided is based on the data available in the ontology and may not account for all possible drug interactions. Users are strongly advised to consult a licensed healthcare provider before making any decisions based on the analysis results. The creators of this application are not responsible for any decisions made or actions taken based on the information provided.</p>
|
238 |
</div>
|
239 |
""", unsafe_allow_html=True)
|
240 |
-
|
241 |
if __name__ == "__main__":
|
242 |
-
main()
|
|
|
36 |
class GraphState:
|
37 |
"""State type for the graph."""
|
38 |
input: str
|
39 |
+
normalized_input: Optional[str] = None
|
40 |
query: Optional[str] = None
|
41 |
ontology_results: Optional[str] = None
|
42 |
response: Optional[str] = None
|
|
|
53 |
logging.error(f"Failed to load ontology file: {e}")
|
54 |
raise ValueError(f"Failed to load ontology file: {e}")
|
55 |
|
56 |
+
def normalize_input_node(state: GraphState) -> Dict[str, str]:
|
57 |
+
"""Normalize drug names using LLM to correct spelling and case."""
|
58 |
+
valid_drugs = [
|
59 |
+
"Warfarin", "Aspirin", "Simvastatin", "Erythromycin", "Metformin",
|
60 |
+
"Ciprofloxacin", "Lisinopril", "Spironolactone", "Clopidogrel",
|
61 |
+
"Omeprazole", "Apixaban", "Rosuvastatin", "Empagliflozin", "Losartan",
|
62 |
+
"Pantoprazole", "Metronidazole", "Theophylline", "Atorvastatin",
|
63 |
+
"Phenelzine", "Ibuprofen", "Naproxen", "Amlodipine", "Nifedipine",
|
64 |
+
"Esomeprazole", "Glucophage", "Sertraline", "Fluoxetine"
|
65 |
+
]
|
66 |
+
|
67 |
+
template = """
|
68 |
+
You are a pharmaceutical expert. Your task is to correct any spelling mistakes and ensure proper
|
69 |
+
capitalization of the following drug names (separated by commas). You must only suggest drugs from
|
70 |
+
the following valid list:
|
71 |
+
|
72 |
+
Valid drugs: {valid_drugs}
|
73 |
+
|
74 |
+
Original drug names: {input}
|
75 |
+
|
76 |
+
Rules:
|
77 |
+
1. Only suggest drugs from the valid list
|
78 |
+
2. If a drug is not in the valid list, respond with "Drug not in the Ontology because this is a Demo version"
|
79 |
+
3. For drugs like "Glucophage", also recognize it as "Metformin" as they are the same medication
|
80 |
+
4. Provide the corrected names in a comma-separated format
|
81 |
+
5. If none of the input drugs match or are similar to the valid list, respond with "None of the provided drugs are available in this demo version"
|
82 |
+
|
83 |
+
Please provide the corrected drug names in a comma-separated format only, without any additional text.
|
84 |
+
|
85 |
+
Examples:
|
86 |
+
Input: "ciprofloxacin, lisinopril"
|
87 |
+
Output: "Ciprofloxacin, Lisinopril"
|
88 |
+
"""
|
89 |
+
|
90 |
+
prompt = ChatPromptTemplate.from_template(template)
|
91 |
+
|
92 |
+
try:
|
93 |
+
llm = ChatGroq(
|
94 |
+
model_name="llama-3.3-70b-versatile",
|
95 |
+
api_key=GROQ_API_KEY,
|
96 |
+
temperature=0.1 # Lower temperature for more consistent results
|
97 |
+
)
|
98 |
+
|
99 |
+
chain = prompt | llm
|
100 |
+
response = chain.invoke({
|
101 |
+
"input": state.input,
|
102 |
+
"valid_drugs": ", ".join(valid_drugs)
|
103 |
+
})
|
104 |
+
normalized_input = response.content.strip()
|
105 |
+
|
106 |
+
# Remove any quotes that might be in the response
|
107 |
+
normalized_input = normalized_input.replace('"', '')
|
108 |
+
|
109 |
+
# Handle invalid responses with more user-friendly messages
|
110 |
+
if normalized_input in ["Drug not in the Ontology because this is a Demo version", "None of the provided drugs are available in this demo version"]:
|
111 |
+
logging.warning(f"Drugs not in demo ontology: {state.input}")
|
112 |
+
return {"normalized_input": "The specified medication(s) are not available in this demo version. Please try medications from the ontology."}
|
113 |
+
|
114 |
+
# Verify that all normalized drugs are in the valid list
|
115 |
+
normalized_drugs = [drug.strip() for drug in normalized_input.split(",")]
|
116 |
+
|
117 |
+
# Debug logging
|
118 |
+
logging.info(f"Normalized drugs: {normalized_drugs}")
|
119 |
+
logging.info(f"Valid drugs: {valid_drugs}")
|
120 |
+
|
121 |
+
valid_check = all(drug in valid_drugs for drug in normalized_drugs)
|
122 |
+
logging.info(f"Valid check result: {valid_check}")
|
123 |
+
|
124 |
+
if not valid_check:
|
125 |
+
invalid_drugs = [drug for drug in normalized_drugs if drug not in valid_drugs]
|
126 |
+
logging.warning(f"Invalid drugs found: {invalid_drugs}")
|
127 |
+
return {"normalized_input": "Some of the specified medications are not available in this demo version. Please use medications from the valid list shown above."}
|
128 |
+
|
129 |
+
logging.info(f"Normalized drug names: {normalized_input}")
|
130 |
+
return {"normalized_input": normalized_input}
|
131 |
+
|
132 |
+
except Exception as e:
|
133 |
+
logging.error(f"Error in drug name normalization: {e}")
|
134 |
+
return {"normalized_input": state.input} # Fall back to original input
|
135 |
+
|
136 |
def create_agent_graph(owl_file_path: str) -> StateGraph:
|
137 |
"""Create a processing graph for drug interaction analysis using separate agents."""
|
138 |
analyzer = DrugInteractionAnalyzer(owl_file_path)
|
139 |
|
140 |
def user_input_node(state: GraphState) -> Dict[str, str]:
|
141 |
+
logging.info("Processing normalized user input.")
|
142 |
+
return {"query": state.normalized_input}
|
143 |
|
144 |
def ontology_query_node(state: GraphState) -> Dict[str, str]:
|
145 |
try:
|
146 |
logging.info("Executing ontology queries.")
|
147 |
+
drug_names = [d.strip() for d in state.normalized_input.split(",")]
|
148 |
results = analyzer.analyze_drugs(drug_names)
|
149 |
logging.info(f"Ontology query results: {results}")
|
150 |
return {"ontology_results": json.dumps(results, indent=2)}
|
|
|
157 |
Based on the drug interaction analysis results:
|
158 |
{ontology_results}
|
159 |
|
160 |
+
Original drug names: {input}
|
161 |
+
Normalized drug names: {normalized_input}
|
162 |
+
|
163 |
Please provide a comprehensive summary of:
|
164 |
1. Direct interactions between the drugs
|
165 |
2. Potential conflicts
|
|
|
168 |
|
169 |
If no results were found, please indicate this clearly.
|
170 |
Format the response in a clear, structured manner.
|
171 |
+
Also mention if any drug names were corrected during normalization.
|
172 |
"""
|
173 |
|
174 |
prompt = ChatPromptTemplate.from_template(template)
|
175 |
|
176 |
try:
|
177 |
llm = ChatGroq(
|
178 |
+
model_name="llama-3.3-70b-versatile",
|
179 |
api_key=GROQ_API_KEY,
|
180 |
temperature=0.7
|
181 |
)
|
|
|
188 |
|
189 |
try:
|
190 |
response = chain.invoke({
|
191 |
+
"ontology_results": state.ontology_results,
|
192 |
+
"input": state.input,
|
193 |
+
"normalized_input": state.normalized_input
|
194 |
})
|
195 |
|
196 |
logging.info("LLM processing completed successfully.")
|
|
|
199 |
logging.error(f"Error processing results with LLM: {e}")
|
200 |
return {"response": f"Error processing results: {str(e)}"}
|
201 |
|
202 |
+
# Create and configure the graph
|
203 |
workflow = StateGraph(GraphState)
|
204 |
|
205 |
+
# Add nodes
|
206 |
+
workflow.add_node("normalize_input", normalize_input_node)
|
207 |
workflow.add_node("input_processor", user_input_node)
|
208 |
workflow.add_node("ontology_query", ontology_query_node)
|
209 |
workflow.add_node("llm_processing", llm_processing_node)
|
210 |
|
211 |
+
# Add edges
|
212 |
+
workflow.add_edge("normalize_input", "input_processor")
|
213 |
workflow.add_edge("input_processor", "ontology_query")
|
214 |
workflow.add_edge("ontology_query", "llm_processing")
|
215 |
|
216 |
+
# Set entry point
|
217 |
+
workflow.set_entry_point("normalize_input")
|
218 |
|
219 |
logging.info("Agent graph created and configured successfully.")
|
220 |
|
|
|
298 |
user_input = st.text_input("", value="", key="drug_input", placeholder="e.g., Aspirin, Warfarin")
|
299 |
st.markdown('<style>div[data-testid="stTextInput"] input { font-size: 16px;}</style>', unsafe_allow_html=True)
|
300 |
|
301 |
+
if st.button("Analyze", type="primary"):
|
302 |
if not user_input.strip():
|
303 |
st.warning("Please enter at least one drug name.")
|
304 |
return
|
|
|
313 |
with st.spinner("Analyzing drug interactions..."):
|
314 |
agent_graph = create_agent_graph(owl_file_path)
|
315 |
result = agent_graph.invoke(GraphState(input=user_input))
|
316 |
+
|
317 |
+
# Display normalized input if it's different from original
|
318 |
+
if result.get("normalized_input") and result["normalized_input"] != user_input:
|
319 |
+
st.info(f"Normalized drug names: {result['normalized_input']}")
|
320 |
|
321 |
st.subheader("Analysis Results:")
|
322 |
st.markdown(result["response"])
|
|
|
334 |
<p style='text-align: left; color: #d46c6c;'>Disclaimer: </p><p style='text-align: left; color: #707377;'>This application is intended for informational purposes only and does not replace professional medical advice, diagnosis, or treatment. The analysis provided is based on the data available in the ontology and may not account for all possible drug interactions. Users are strongly advised to consult a licensed healthcare provider before making any decisions based on the analysis results. The creators of this application are not responsible for any decisions made or actions taken based on the information provided.</p>
|
335 |
</div>
|
336 |
""", unsafe_allow_html=True)
|
337 |
+
|
338 |
if __name__ == "__main__":
|
339 |
+
main()
|