Ali2206 commited on
Commit
1bb8be7
·
verified ·
1 Parent(s): 8802f56

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -133
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
- # Helper: format assistant responses in collapsible 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; padding: 8px; margin-top: 8px;'>"
51
- "<summary style='font-weight: bold;'>Answer</summary>"
52
- f"<pre style='white-space: pre-wrap;'>{formatted}</pre>"
53
- "</details>"
54
- )
55
-
56
- # === UI setup
57
- def create_ui(agent):
58
- with gr.Blocks() as demo:
59
- gr.Markdown("<h1 style='text-align: center;'>TxAgent: Therapeutic Reasoning</h1>")
60
- gr.Markdown("Ask biomedical or therapeutic questions. Powered by step-by-step reasoning and tools.")
61
-
62
- temperature = gr.Slider(0, 1, value=0.3, label="Temperature")
63
- max_new_tokens = gr.Slider(128, 4096, value=1024, label="Max New Tokens")
64
- max_tokens = gr.Slider(128, 32000, value=8192, label="Max Total Tokens")
65
- max_round = gr.Slider(1, 50, value=30, label="Max Rounds")
66
- multi_agent = gr.Checkbox(label="Enable Multi-agent Reasoning", value=False)
67
- conversation_state = gr.State([])
68
-
69
- chatbot = gr.Chatbot(label="TxAgent", height=600, type="messages")
70
- message_input = gr.Textbox(placeholder="Ask your biomedical question...", show_label=False)
71
- send_button = gr.Button("Send", variant="primary")
72
-
73
- # Main handler
74
- def handle_chat(message, history, temperature, max_new_tokens, max_tokens, multi_agent, conversation, max_round):
75
- generator = agent.run_gradio_chat(
76
- message=message,
77
- history=history,
78
- temperature=temperature,
79
- max_new_tokens=max_new_tokens,
80
- max_token=max_tokens,
81
- call_agent=multi_agent,
82
- conversation=conversation,
83
- max_round=max_round
84
- )
85
-
86
- for update in generator:
87
- formatted = []
88
- for m in update:
89
- role = m["role"] if isinstance(m, dict) else getattr(m, "role", "assistant")
90
- content = m["content"] if isinstance(m, dict) else getattr(m, "content", "")
91
-
92
- if role == "assistant":
93
- content = format_collapsible(content)
94
-
95
- formatted.append({"role": role, "content": content})
96
- yield formatted
97
-
98
- # Button and Enter triggers
99
- inputs = [message_input, chatbot, temperature, max_new_tokens, max_tokens, multi_agent, conversation_state, max_round]
100
- send_button.click(fn=handle_chat, inputs=inputs, outputs=chatbot)
101
- message_input.submit(fn=handle_chat, inputs=inputs, outputs=chatbot)
102
-
103
- gr.Examples(examples=question_examples, inputs=message_input)
104
- gr.Markdown("**DISCLAIMER**: This demo is for research purposes only and does not provide medical advice.")
105
-
106
- return demo
107
-
108
- # === Entry point
109
- if __name__ == "__main__":
110
- freeze_support()
111
-
112
- try:
113
- agent = TxAgent(
114
- model_name=model_name,
115
- rag_model_name=rag_model_name,
116
- tool_files_dict=new_tool_files,
117
- force_finish=True,
118
- enable_checker=True,
119
- step_rag_num=10,
120
- seed=100,
121
- additional_default_tools=[] # Avoid loading unimplemented tools
122
- )
123
- agent.init_model()
124
-
125
- if not hasattr(agent, "run_gradio_chat"):
126
- raise AttributeError("TxAgent missing run_gradio_chat")
127
-
128
- demo = create_ui(agent)
129
- demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
130
-
131
- except Exception as e:
132
- print(f"❌ App failed to start: {e}")
133
- raise
 
 
 
 
 
 
 
 
 
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