yashbyname commited on
Commit
a4acb7d
·
verified ·
1 Parent(s): 7427814

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -38
app.py CHANGED
@@ -207,16 +207,32 @@ def submit_query(session_id, query):
207
  'apikey': api_key,
208
  'Content-Type': 'application/json'
209
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  submit_query_body = {
211
  "endpointId": "predefined-openai-gpt4o",
212
- "query": query,
213
  "pluginIds": ["plugin-1712327325", "plugin-1713962163"],
214
  "responseMode": "sync"
215
  }
216
 
217
  logger.info(f"Submitting query for session {session_id}")
218
- logger.info(f"Query content: {query}")
219
-
220
  response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
221
  response.raise_for_status()
222
 
@@ -230,44 +246,39 @@ def submit_query(session_id, query):
230
  logger.error(f"Response content: {e.response.text}")
231
  raise
232
 
233
- def gradio_interface(patient_info, query_type):
 
 
 
 
 
 
 
 
234
  try:
235
  # Create session
236
  session_id = create_chat_session()
237
 
238
- # Construct query
239
- query = f"Patient Info: {patient_info}\nQuery Type: {query_type}"
240
-
241
  # Submit query and get response
242
- llm_response = submit_query(session_id, query)
243
 
244
  # Enhanced response handling
245
- if not llm_response:
246
- logger.error("Empty response received from LLM")
247
- return "Error: No response received from the LLM service"
248
-
249
- # Navigate the response structure with detailed logging
250
- logger.info(f"Processing LLM response: {json.dumps(llm_response, indent=2)}")
251
-
252
- # Check for answer in the correct field
253
- if 'data' not in llm_response or 'answer' not in llm_response['data']:
254
- logger.error("Response missing required fields")
255
- return f"Error: Unexpected response structure\nFull response: {json.dumps(llm_response, indent=2)}"
256
 
 
257
  answer = llm_response['data']['answer']
258
- if not answer:
259
- logger.error("No answer found in response data")
260
- return f"Error: No answer in response\nFull response: {json.dumps(llm_response, indent=2)}"
261
 
262
- # Format the response
263
- response = f"Patient Info: {patient_info}\n\nQuery Type: {query_type}\n\nAnalysis:\n{answer}"
 
264
 
265
- # Add completion metrics if available
266
- if 'metrics' in llm_response['data']:
267
- metrics = llm_response['data']['metrics']
268
- response += f"\n\nProcessing Time: {metrics.get('totalTimeSec', 'N/A')} seconds"
269
 
270
- return response
271
 
272
  except Exception as e:
273
  logger.error(f"Error in gradio_interface: {str(e)}", exc_info=True)
@@ -279,18 +290,21 @@ iface = gr.Interface(
279
  inputs=[
280
  gr.Textbox(
281
  label="Patient Information",
282
- placeholder="Enter patient details here...",
283
  lines=5,
284
  max_lines=10
285
- ),
286
- gr.Textbox(
287
- label="Query Type",
288
- placeholder="Describe the type of diagnosis or information needed..."
289
- ),
290
  ],
291
- outputs=gr.Textbox(label="Response", placeholder="The response will appear here..."),
292
- title="Medical Diagnosis with LLM",
293
- description="Provide patient information and a query type for analysis by the LLM."
 
 
 
 
 
 
 
294
  )
295
 
296
  if __name__ == "__main__":
 
207
  'apikey': api_key,
208
  'Content-Type': 'application/json'
209
  }
210
+
211
+ # Structured prompt to get JSON response
212
+ structured_query = f"""
213
+ Based on the following patient information, provide a detailed medical analysis in JSON format:
214
+
215
+ {query}
216
+
217
+ Please structure your response in valid JSON format with the following fields:
218
+ - diagnosis_details: Overall diagnosis analysis
219
+ - probable_diagnoses: Array of most probable diagnoses, ordered by likelihood
220
+ - treatment_plans: Array of recommended treatment plans
221
+ - lifestyle_modifications: Array of recommended lifestyle changes
222
+ - medications: Array of recommended medications with dosages
223
+ - additional_tests: Array of recommended additional tests or examinations
224
+ - precautions: Array of important precautions or warnings
225
+ - follow_up: Recommended follow-up timeline and actions
226
+ """
227
+
228
  submit_query_body = {
229
  "endpointId": "predefined-openai-gpt4o",
230
+ "query": structured_query,
231
  "pluginIds": ["plugin-1712327325", "plugin-1713962163"],
232
  "responseMode": "sync"
233
  }
234
 
235
  logger.info(f"Submitting query for session {session_id}")
 
 
236
  response = requests.post(submit_query_url, headers=submit_query_headers, json=submit_query_body)
237
  response.raise_for_status()
238
 
 
246
  logger.error(f"Response content: {e.response.text}")
247
  raise
248
 
249
+ def format_json_response(json_str):
250
+ """Format the JSON response for better readability"""
251
+ try:
252
+ data = json.loads(json_str)
253
+ return json.dumps(data, indent=2)
254
+ except json.JSONDecodeError:
255
+ return json_str
256
+
257
+ def gradio_interface(patient_info):
258
  try:
259
  # Create session
260
  session_id = create_chat_session()
261
 
 
 
 
262
  # Submit query and get response
263
+ llm_response = submit_query(session_id, patient_info)
264
 
265
  # Enhanced response handling
266
+ if not llm_response or 'data' not in llm_response or 'answer' not in llm_response['data']:
267
+ logger.error("Invalid response structure")
268
+ return "Error: Invalid response from the LLM service"
 
 
 
 
 
 
 
 
269
 
270
+ # Get the answer and format it
271
  answer = llm_response['data']['answer']
272
+ formatted_answer = format_json_response(answer)
 
 
273
 
274
+ # Add processing metrics
275
+ metrics = llm_response['data'].get('metrics', {})
276
+ processing_time = metrics.get('totalTimeSec', 'N/A')
277
 
278
+ # Combine the response
279
+ full_response = f"Analysis Results (Processing Time: {processing_time} seconds):\n\n{formatted_answer}"
 
 
280
 
281
+ return full_response
282
 
283
  except Exception as e:
284
  logger.error(f"Error in gradio_interface: {str(e)}", exc_info=True)
 
290
  inputs=[
291
  gr.Textbox(
292
  label="Patient Information",
293
+ placeholder="Enter patient details including: symptoms, medical history, current medications, age, gender, and any relevant test results...",
294
  lines=5,
295
  max_lines=10
296
+ )
 
 
 
 
297
  ],
298
+ outputs=gr.Textbox(
299
+ label="Medical Analysis",
300
+ placeholder="The analysis will appear here in JSON format...",
301
+ lines=15
302
+ ),
303
+ title="Medical Diagnosis Assistant",
304
+ description="""
305
+ Enter detailed patient information to receive a structured medical analysis.
306
+ The system will provide diagnosis possibilities, treatment recommendations, and other relevant medical advice in JSON format.
307
+ """
308
  )
309
 
310
  if __name__ == "__main__":