Ali2206 commited on
Commit
fe2e04a
·
verified ·
1 Parent(s): 671fca8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -51
app.py CHANGED
@@ -5,6 +5,7 @@ from multiprocessing import freeze_support
5
  import importlib
6
  import inspect
7
  import json
 
8
 
9
  # === Fix path to include src/txagent
10
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
@@ -14,10 +15,13 @@ import txagent.txagent
14
  importlib.reload(txagent.txagent)
15
  from txagent.txagent import TxAgent
16
 
17
- # === Debug print
18
  print(">>> TxAgent loaded from:", inspect.getfile(TxAgent))
19
  print(">>> TxAgent has run_gradio_chat:", hasattr(TxAgent, "run_gradio_chat"))
20
 
 
 
 
21
  # === Environment
22
  current_dir = os.path.abspath(os.path.dirname(__file__))
23
  os.environ["MKL_THREADING_LAYER"] = "GNU"
@@ -36,63 +40,44 @@ question_examples = [
36
  ["What treatment options exist for HER2+ breast cancer resistant to trastuzumab?"]
37
  ]
38
 
39
- # === Helper: extract tool name from content
40
- def extract_tool_name_and_clean_content(message_obj):
41
- import logging
42
- logging.basicConfig(level=logging.INFO)
43
-
44
  tool_name = "Tool Result"
45
- content = ""
46
-
47
- if isinstance(message_obj, dict):
48
- role = message_obj.get("role", "assistant")
49
- content = message_obj.get("content", "")
50
- tool_calls = message_obj.get("tool_calls", None)
51
- else:
52
- role = getattr(message_obj, "role", "assistant")
53
- content = getattr(message_obj, "content", "")
54
- tool_calls = getattr(message_obj, "tool_calls", None)
55
-
56
- # Try to extract tool name from `tool_calls`
57
  if tool_calls:
58
  try:
59
  if isinstance(tool_calls, str):
60
- import json
61
  tool_calls = json.loads(tool_calls)
62
  tool_name = tool_calls[0].get("name", "Tool Result")
63
- logging.info(f"[extract_tool_name] Extracted from tool_calls: {tool_name}")
64
  except Exception as e:
65
- logging.warning(f"[extract_tool_name] Failed tool_calls parsing: {e}")
66
 
67
- # Format clean output
68
  if isinstance(content, (dict, list)):
69
- formatted = json.dumps(content, indent=2)
70
- else:
71
- formatted = str(content)
72
-
73
- return f"Tool: {tool_name}", formatted
74
 
75
-
76
- # === Helper: formatted collapsible output
77
  def format_collapsible(content, title="Answer"):
78
  return (
79
- f"<details style='border: 1px solid #ccc; padding: 8px; margin-top: 8px;'>"
80
- f"<summary style='font-weight: bold;'>{title}</summary>"
81
- f"<div style='margin-top: 8px; white-space: pre-wrap;'>{content}</div></details>"
82
  )
83
 
84
- # === UI creation
85
  def create_ui(agent):
86
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
87
- gr.Markdown("<h1 style='text-align: center;'>TxAgent: Therapeutic Reasoning</h1>")
88
- gr.Markdown("Ask biomedical or therapeutic questions. Powered by step-by-step reasoning and tools.")
89
 
90
  chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
91
- message_input = gr.Textbox(placeholder="Ask your biomedical question...", show_label=False)
92
  send_button = gr.Button("Send", variant="primary")
93
  conversation_state = gr.State([])
94
 
95
- # === Core handler (streaming generator)
96
  def handle_chat(message, history, conversation):
97
  generator = agent.run_gradio_chat(
98
  message=message,
@@ -104,32 +89,30 @@ def create_ui(agent):
104
  conversation=conversation,
105
  max_round=30
106
  )
107
-
108
  for update in generator:
109
- formatted_messages = []
110
  for m in update:
111
- role = m["role"] if isinstance(m, dict) else getattr(m, "role", "assistant")
112
- content = m["content"] if isinstance(m, dict) else getattr(m, "content", "")
113
  if role == "assistant":
114
- title, clean = extract_tool_name_and_clean_content(content)
115
  content = format_collapsible(clean, title)
116
- formatted_messages.append({"role": role, "content": content})
117
- yield formatted_messages
 
 
118
 
119
- # === Trigger handlers
120
  inputs = [message_input, chatbot, conversation_state]
121
  send_button.click(fn=handle_chat, inputs=inputs, outputs=chatbot)
122
  message_input.submit(fn=handle_chat, inputs=inputs, outputs=chatbot)
123
 
124
  gr.Examples(examples=question_examples, inputs=message_input)
125
- gr.Markdown("**DISCLAIMER**: This demo is for research purposes only and does not provide medical advice.")
126
 
127
  return demo
128
 
129
- # === Startup
130
  if __name__ == "__main__":
131
  freeze_support()
132
-
133
  try:
134
  agent = TxAgent(
135
  model_name=model_name,
@@ -150,10 +133,8 @@ if __name__ == "__main__":
150
  demo.queue().launch(
151
  server_name="0.0.0.0",
152
  server_port=7860,
153
- show_error=True,
154
- share=True
155
  )
156
-
157
  except Exception as e:
158
  print(f"❌ App failed to start: {e}")
159
  raise
 
5
  import importlib
6
  import inspect
7
  import json
8
+ import logging
9
 
10
  # === Fix path to include src/txagent
11
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
 
15
  importlib.reload(txagent.txagent)
16
  from txagent.txagent import TxAgent
17
 
18
+ # === Debug info
19
  print(">>> TxAgent loaded from:", inspect.getfile(TxAgent))
20
  print(">>> TxAgent has run_gradio_chat:", hasattr(TxAgent, "run_gradio_chat"))
21
 
22
+ # === Logging
23
+ logging.basicConfig(level=logging.INFO)
24
+
25
  # === Environment
26
  current_dir = os.path.abspath(os.path.dirname(__file__))
27
  os.environ["MKL_THREADING_LAYER"] = "GNU"
 
40
  ["What treatment options exist for HER2+ breast cancer resistant to trastuzumab?"]
41
  ]
42
 
43
+ # === Extract tool name and format output
44
+ def extract_tool_name_and_clean_content(msg):
 
 
 
45
  tool_name = "Tool Result"
46
+ content = msg.get("content") if isinstance(msg, dict) else getattr(msg, "content", "")
47
+ tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else getattr(msg, "tool_calls", None)
48
+
 
 
 
 
 
 
 
 
 
49
  if tool_calls:
50
  try:
51
  if isinstance(tool_calls, str):
 
52
  tool_calls = json.loads(tool_calls)
53
  tool_name = tool_calls[0].get("name", "Tool Result")
54
+ logging.info(f"[extract_tool_name] Parsed tool name: {tool_name}")
55
  except Exception as e:
56
+ logging.warning(f"[extract_tool_name] Failed parsing tool_calls: {e}")
57
 
 
58
  if isinstance(content, (dict, list)):
59
+ content = json.dumps(content, indent=2)
60
+ return f"Tool: {tool_name}", content
 
 
 
61
 
62
+ # === Format answer in collapsible box
 
63
  def format_collapsible(content, title="Answer"):
64
  return (
65
+ f"<details style='border: 1px solid #ccc; border-radius: 8px; padding: 10px; margin-top: 10px;'>"
66
+ f"<summary style='font-size: 16px; font-weight: bold; color: #3B82F6;'>{title}</summary>"
67
+ f"<div style='margin-top: 8px; font-size: 15px; line-height: 1.6; white-space: pre-wrap;'>{content}</div></details>"
68
  )
69
 
70
+ # === Build UI
71
  def create_ui(agent):
72
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
73
+ gr.Markdown("<h1 style='text-align: center;'>💊 TxAgent: Therapeutic Reasoning</h1>")
74
+ gr.Markdown("Ask biomedical or therapeutic questions. Powered by tool-augmented reasoning.")
75
 
76
  chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
77
+ message_input = gr.Textbox(placeholder="Ask a biomedical question...", show_label=False)
78
  send_button = gr.Button("Send", variant="primary")
79
  conversation_state = gr.State([])
80
 
 
81
  def handle_chat(message, history, conversation):
82
  generator = agent.run_gradio_chat(
83
  message=message,
 
89
  conversation=conversation,
90
  max_round=30
91
  )
 
92
  for update in generator:
93
+ formatted = []
94
  for m in update:
95
+ role = m.get("role") if isinstance(m, dict) else getattr(m, "role", "assistant")
 
96
  if role == "assistant":
97
+ title, clean = extract_tool_name_and_clean_content(m)
98
  content = format_collapsible(clean, title)
99
+ else:
100
+ content = m.get("content") if isinstance(m, dict) else getattr(m, "content", "")
101
+ formatted.append({"role": role, "content": content})
102
+ yield formatted
103
 
 
104
  inputs = [message_input, chatbot, conversation_state]
105
  send_button.click(fn=handle_chat, inputs=inputs, outputs=chatbot)
106
  message_input.submit(fn=handle_chat, inputs=inputs, outputs=chatbot)
107
 
108
  gr.Examples(examples=question_examples, inputs=message_input)
109
+ gr.Markdown("<small style='color: gray;'>DISCLAIMER: This demo is for research purposes only and does not provide medical advice.</small>")
110
 
111
  return demo
112
 
113
+ # === Main
114
  if __name__ == "__main__":
115
  freeze_support()
 
116
  try:
117
  agent = TxAgent(
118
  model_name=model_name,
 
133
  demo.queue().launch(
134
  server_name="0.0.0.0",
135
  server_port=7860,
136
+ show_error=True
 
137
  )
 
138
  except Exception as e:
139
  print(f"❌ App failed to start: {e}")
140
  raise