File size: 5,093 Bytes
4b0f1a8
511fb62
5ffaf72
9aeb1dd
0151c98
9aeb1dd
0151c98
9438945
511fb62
 
410d25f
1a87180
b301866
 
99cd953
1a87180
 
b301866
0151c98
79fb3cd
 
 
 
 
 
 
511fb62
5ffaf72
12efdad
59ced24
 
a87f861
a893249
59ced24
9438945
 
 
 
79fb3cd
a87f861
12efdad
70839bb
e3711be
 
 
6916257
 
5ffaf72
709aba9
 
6916257
5ffaf72
e3711be
 
 
6916257
 
709aba9
 
6916257
 
 
 
5ffaf72
1a87180
6916257
 
 
 
5ffaf72
6916257
 
e6865f5
 
1a87180
5205ee8
5ffaf72
 
57027dc
79fb3cd
6d40680
709aba9
5ffaf72
 
 
 
 
 
 
 
 
57027dc
5ffaf72
fc30674
951cbe7
60a4dae
 
57027dc
951cbe7
 
 
57027dc
 
951cbe7
 
 
709aba9
951cbe7
 
6d40680
709aba9
 
5ffaf72
e6865f5
5ffaf72
709aba9
 
 
 
 
 
5ffaf72
709aba9
 
6d40680
709aba9
 
511fb62
79fb3cd
511fb62
5ffaf72
 
 
e0a0615
70839bb
 
b301866
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
134
135
136
137
138
import os
import json
import torch
import logging
import numpy
import gradio as gr
import torch.serialization
from importlib.resources import files
from txagent import TxAgent
from tooluniverse import ToolUniverse

# Allow loading old numpy types with torch.load
torch.serialization.add_safe_globals([
    numpy.core.multiarray._reconstruct,
    numpy.ndarray,
    numpy.dtype,
    numpy.dtypes.Float32DType
])

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

os.environ["MKL_THREADING_LAYER"] = "GNU"
os.environ["TOKENIZERS_PARALLELISM"] = "false"
current_dir = os.path.dirname(os.path.abspath(__file__))

CONFIG = {
    "model_name": "mims-harvard/TxAgent-T1-Llama-3.1-8B",
    "rag_model_name": "mims-harvard/ToolRAG-T1-GTE-Qwen2-1.5B",
    "embedding_filename": "ToolRAG-T1-GTE-Qwen2-1.5Btool_embedding.pt",
    "tool_files": {
        "opentarget": str(files('tooluniverse.data').joinpath('opentarget_tools.json')),
        "fda_drug_label": str(files('tooluniverse.data').joinpath('fda_drug_labeling_tools.json')),
        "special_tools": str(files('tooluniverse.data').joinpath('special_tools.json')),
        "monarch": str(files('tooluniverse.data').joinpath('monarch_tools.json')),
        "new_tool": os.path.join(current_dir, 'data', 'new_tool.json')
    }
}

def prepare_tool_files():
    os.makedirs(os.path.join(current_dir, 'data'), exist_ok=True)
    if not os.path.exists(CONFIG["tool_files"]["new_tool"]):
        try:
            tu = ToolUniverse()
            tools = tu.get_all_tools() if hasattr(tu, "get_all_tools") else getattr(tu, "tools", [])
            with open(CONFIG["tool_files"]["new_tool"], "w") as f:
                json.dump(tools, f, indent=2)
        except Exception as e:
            logger.error(f"Tool generation failed: {e}")

def create_agent():
    prepare_tool_files()
    try:
        agent = TxAgent(
            CONFIG["model_name"],
            CONFIG["rag_model_name"],
            tool_files_dict=CONFIG["tool_files"],
            force_finish=True,
            enable_checker=True,
            step_rag_num=10,
            seed=42,
            additional_default_tools=["DirectResponse", "RequireClarification"]
        )
        agent.init_model()
        return agent
    except Exception as e:
        logger.error(f"Agent initialization failed: {e}")
        raise

def respond(msg, chat_history, temperature, max_new_tokens, max_tokens, multi_agent, conversation, max_round):
    if not isinstance(msg, str) or len(msg.strip()) <= 10:
        return chat_history + [{"role": "assistant", "content": "Hi, I am TxAgent. Please provide a valid message longer than 10 characters."}]

    message = msg.strip()
    chat_history.append({"role": "user", "content": message})
    formatted_history = [(m["role"], m["content"]) for m in chat_history if "role" in m and "content" in m]

    try:
        response_generator = agent.run_gradio_chat(
            message=message,
            history=formatted_history,
            temperature=temperature,
            max_new_tokens=max_new_tokens,
            max_token=max_tokens,
            call_agent=multi_agent,
            conversation=conversation,
            max_round=max_round,
            seed=42,
            call_agent_level=None,
            sub_agent_task=None
        )

        collected = ""
        for chunk in response_generator:
            if isinstance(chunk, dict) and "content" in chunk:
                collected += chunk["content"]
            elif isinstance(chunk, str):
                collected += chunk
            elif chunk is not None:
                collected += str(chunk)

        chat_history.append({"role": "assistant", "content": collected or "⚠️ No content returned."})

    except Exception as e:
        chat_history.append({"role": "assistant", "content": f"❌ Error: {str(e)}"})

    return chat_history

def create_demo(agent):
    with gr.Blocks(css=".gr-button { font-size: 18px !important; }") as demo:
        chatbot = gr.Chatbot(label="TxAgent", type="messages", render_markdown=True)
        msg = gr.Textbox(label="Your question", placeholder="Ask a biomedical question...", scale=6)
        with gr.Row():
            temp = gr.Slider(0, 1, value=0.3, label="Temperature")
            max_new_tokens = gr.Slider(128, 4096, value=1024, label="Max New Tokens")
            max_tokens = gr.Slider(128, 81920, value=81920, label="Max Total Tokens")
            max_rounds = gr.Slider(1, 30, value=30, label="Max Rounds")
            multi_agent = gr.Checkbox(label="Multi-Agent Mode")
        submit = gr.Button("Ask TxAgent")
        submit.click(
            respond,
            inputs=[msg, chatbot, temp, max_new_tokens, max_tokens, multi_agent, gr.State([]), max_rounds],
            outputs=[chatbot]
        )
    return demo

def main():
    global agent
    agent = create_agent()
    demo = create_demo(agent)
    demo.queue(concurrency_count=1, max_size=20).launch(share=True)

if __name__ == "__main__":
    main()