Update app.py
Browse files
app.py
CHANGED
|
@@ -1,133 +1,141 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import sys
|
| 3 |
-
import gradio as gr
|
| 4 |
-
from multiprocessing import freeze_support
|
| 5 |
-
import importlib
|
| 6 |
-
import inspect
|
| 7 |
-
import json
|
| 8 |
-
|
| 9 |
-
# Fix path to include src
|
| 10 |
-
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 11 |
-
|
| 12 |
-
# Reload TxAgent from txagent.py
|
| 13 |
-
import txagent.txagent
|
| 14 |
-
importlib.reload(txagent.txagent)
|
| 15 |
-
from txagent.txagent import TxAgent
|
| 16 |
-
|
| 17 |
-
# Debug info
|
| 18 |
-
print(">>> TxAgent loaded from:", inspect.getfile(TxAgent))
|
| 19 |
-
print(">>> TxAgent has run_gradio_chat:", hasattr(TxAgent, "run_gradio_chat"))
|
| 20 |
-
|
| 21 |
-
# Env vars
|
| 22 |
-
current_dir = os.path.abspath(os.path.dirname(__file__))
|
| 23 |
-
os.environ["MKL_THREADING_LAYER"] = "GNU"
|
| 24 |
-
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 25 |
-
|
| 26 |
-
# Model config
|
| 27 |
-
model_name = "mims-harvard/TxAgent-T1-Llama-3.1-8B"
|
| 28 |
-
rag_model_name = "mims-harvard/ToolRAG-T1-GTE-Qwen2-1.5B"
|
| 29 |
-
new_tool_files = {
|
| 30 |
-
"new_tool": os.path.join(current_dir, "data", "new_tool.json")
|
| 31 |
-
}
|
| 32 |
-
|
| 33 |
-
# Sample questions
|
| 34 |
-
question_examples = [
|
| 35 |
-
["Given a patient with WHIM syndrome on prophylactic antibiotics, is it advisable to co-administer Xolremdi with fluconazole?"],
|
| 36 |
-
["What treatment options exist for HER2+ breast cancer resistant to trastuzumab?"]
|
| 37 |
-
]
|
| 38 |
-
|
| 39 |
-
#
|
| 40 |
-
def format_collapsible(content):
|
| 41 |
-
if isinstance(content, (dict, list)):
|
| 42 |
-
try:
|
| 43 |
-
formatted = json.dumps(content, indent=2)
|
| 44 |
-
except Exception:
|
| 45 |
-
formatted = str(content)
|
| 46 |
-
else:
|
| 47 |
-
formatted = str(content)
|
| 48 |
-
|
| 49 |
-
return (
|
| 50 |
-
"<details style='border: 1px solid #ccc; padding:
|
| 51 |
-
"<summary style='font-weight:
|
| 52 |
-
f"<pre style='white-space: pre-wrap;'>{formatted}</pre>"
|
| 53 |
-
"</details>"
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
#
|
| 57 |
-
def create_ui(agent):
|
| 58 |
-
with gr.Blocks(
|
| 59 |
-
|
| 60 |
-
gr
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from multiprocessing import freeze_support
|
| 5 |
+
import importlib
|
| 6 |
+
import inspect
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
# Fix path to include src
|
| 10 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
|
| 11 |
+
|
| 12 |
+
# Reload TxAgent from txagent.py
|
| 13 |
+
import txagent.txagent
|
| 14 |
+
importlib.reload(txagent.txagent)
|
| 15 |
+
from txagent.txagent import TxAgent
|
| 16 |
+
|
| 17 |
+
# Debug info
|
| 18 |
+
print(">>> TxAgent loaded from:", inspect.getfile(TxAgent))
|
| 19 |
+
print(">>> TxAgent has run_gradio_chat:", hasattr(TxAgent, "run_gradio_chat"))
|
| 20 |
+
|
| 21 |
+
# Env vars
|
| 22 |
+
current_dir = os.path.abspath(os.path.dirname(__file__))
|
| 23 |
+
os.environ["MKL_THREADING_LAYER"] = "GNU"
|
| 24 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 25 |
+
|
| 26 |
+
# Model config
|
| 27 |
+
model_name = "mims-harvard/TxAgent-T1-Llama-3.1-8B"
|
| 28 |
+
rag_model_name = "mims-harvard/ToolRAG-T1-GTE-Qwen2-1.5B"
|
| 29 |
+
new_tool_files = {
|
| 30 |
+
"new_tool": os.path.join(current_dir, "data", "new_tool.json")
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# Sample questions
|
| 34 |
+
question_examples = [
|
| 35 |
+
["Given a patient with WHIM syndrome on prophylactic antibiotics, is it advisable to co-administer Xolremdi with fluconazole?"],
|
| 36 |
+
["What treatment options exist for HER2+ breast cancer resistant to trastuzumab?"]
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
# Format assistant responses in collapsible JSON-style panels
|
| 40 |
+
def format_collapsible(content):
|
| 41 |
+
if isinstance(content, (dict, list)):
|
| 42 |
+
try:
|
| 43 |
+
formatted = json.dumps(content, indent=2)
|
| 44 |
+
except Exception:
|
| 45 |
+
formatted = str(content)
|
| 46 |
+
else:
|
| 47 |
+
formatted = str(content)
|
| 48 |
+
|
| 49 |
+
return (
|
| 50 |
+
"<details style='border: 1px solid #ccc; border-radius: 10px; padding: 12px; margin-top: 10px;'>"
|
| 51 |
+
"<summary style='font-weight: 600; font-size: 16px;'>Answer</summary>"
|
| 52 |
+
f"<pre style='white-space: pre-wrap; font-family: monospace; font-size: 14px;'>{formatted}</pre>"
|
| 53 |
+
"</details>"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# UI setup
|
| 57 |
+
def create_ui(agent):
|
| 58 |
+
with gr.Blocks(css="""
|
| 59 |
+
body { font-family: 'Segoe UI', sans-serif; background-color: #f8f9fa; }
|
| 60 |
+
.gr-button-primary { background: linear-gradient(90deg, #4b6cb7, #182848); color: white; border: none; }
|
| 61 |
+
.gr-button-primary:hover { background: linear-gradient(90deg, #5a78d1, #243b6c); }
|
| 62 |
+
.gr-markdown h1 { margin-bottom: 0; }
|
| 63 |
+
.gr-markdown { margin-bottom: 16px; }
|
| 64 |
+
""") as demo:
|
| 65 |
+
gr.Markdown("<h1 style='text-align: center;'>TxAgent: Therapeutic Reasoning</h1>")
|
| 66 |
+
gr.Markdown("<p style='text-align: center;'>Ask biomedical or therapeutic questions. Powered by tool-augmented reasoning.</p>")
|
| 67 |
+
|
| 68 |
+
with gr.Row():
|
| 69 |
+
with gr.Column():
|
| 70 |
+
temperature = gr.Slider(0, 1, value=0.3, label="Temperature")
|
| 71 |
+
max_new_tokens = gr.Slider(128, 4096, value=1024, label="Max New Tokens")
|
| 72 |
+
max_tokens = gr.Slider(128, 32000, value=8192, label="Max Total Tokens")
|
| 73 |
+
max_round = gr.Slider(1, 50, value=30, label="Max Rounds")
|
| 74 |
+
multi_agent = gr.Checkbox(label="Enable Multi-agent Reasoning", value=False)
|
| 75 |
+
|
| 76 |
+
conversation_state = gr.State([])
|
| 77 |
+
chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
|
| 78 |
+
message_input = gr.Textbox(placeholder="Ask your biomedical question...", show_label=False)
|
| 79 |
+
send_button = gr.Button("Send", variant="primary")
|
| 80 |
+
|
| 81 |
+
# Main handler
|
| 82 |
+
def handle_chat(message, history, temperature, max_new_tokens, max_tokens, multi_agent, conversation, max_round):
|
| 83 |
+
generator = agent.run_gradio_chat(
|
| 84 |
+
message=message,
|
| 85 |
+
history=history,
|
| 86 |
+
temperature=temperature,
|
| 87 |
+
max_new_tokens=max_new_tokens,
|
| 88 |
+
max_token=max_tokens,
|
| 89 |
+
call_agent=multi_agent,
|
| 90 |
+
conversation=conversation,
|
| 91 |
+
max_round=max_round
|
| 92 |
+
)
|
| 93 |
+
for update in generator:
|
| 94 |
+
formatted = []
|
| 95 |
+
for m in update:
|
| 96 |
+
role = m["role"] if isinstance(m, dict) else getattr(m, "role", "assistant")
|
| 97 |
+
content = m["content"] if isinstance(m, dict) else getattr(m, "content", "")
|
| 98 |
+
if role == "assistant":
|
| 99 |
+
content = format_collapsible(content)
|
| 100 |
+
formatted.append({"role": role, "content": content})
|
| 101 |
+
yield formatted
|
| 102 |
+
|
| 103 |
+
inputs = [message_input, chatbot, temperature, max_new_tokens, max_tokens, multi_agent, conversation_state, max_round]
|
| 104 |
+
send_button.click(fn=handle_chat, inputs=inputs, outputs=chatbot)
|
| 105 |
+
message_input.submit(fn=handle_chat, inputs=inputs, outputs=chatbot)
|
| 106 |
+
|
| 107 |
+
gr.Examples(examples=question_examples, inputs=message_input)
|
| 108 |
+
gr.Markdown("<p style='font-size: 12px; color: gray;'>DISCLAIMER: This demo is for research purposes only and does not provide medical advice.</p>")
|
| 109 |
+
|
| 110 |
+
return demo
|
| 111 |
+
|
| 112 |
+
# Entry point
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
freeze_support()
|
| 115 |
+
try:
|
| 116 |
+
agent = TxAgent(
|
| 117 |
+
model_name=model_name,
|
| 118 |
+
rag_model_name=rag_model_name,
|
| 119 |
+
tool_files_dict=new_tool_files,
|
| 120 |
+
force_finish=True,
|
| 121 |
+
enable_checker=True,
|
| 122 |
+
step_rag_num=10,
|
| 123 |
+
seed=100,
|
| 124 |
+
additional_default_tools=[]
|
| 125 |
+
)
|
| 126 |
+
agent.init_model()
|
| 127 |
+
|
| 128 |
+
if not hasattr(agent, "run_gradio_chat"):
|
| 129 |
+
raise AttributeError("TxAgent missing run_gradio_chat")
|
| 130 |
+
|
| 131 |
+
demo = create_ui(agent)
|
| 132 |
+
demo.queue().launch(
|
| 133 |
+
server_name="0.0.0.0",
|
| 134 |
+
server_port=7860,
|
| 135 |
+
share=True,
|
| 136 |
+
show_error=True
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
print(f"\u274c App failed to start: {e}")
|
| 141 |
+
raise
|